-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlobalExceptionHandler.java
More file actions
70 lines (61 loc) · 2.88 KB
/
GlobalExceptionHandler.java
File metadata and controls
70 lines (61 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.micropay.security.exception.handler;
import com.micropay.security.exception.DuplicateObjectException;
import com.micropay.security.exception.NotActiveUserException;
import com.micropay.security.exception.UserNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.micropay.security.dto.response.ErrorResponse;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.LocalDateTime;
import java.util.Objects;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneric(Exception exception) {
ErrorResponse body = new ErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR.value(),
"An unexpected error occurred. Please try again later.",
LocalDateTime.now()
);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
}
@ExceptionHandler(DuplicateObjectException.class)
public ResponseEntity<ErrorResponse> handleDuplicateObjectException(DuplicateObjectException exception) {
ErrorResponse body = new ErrorResponse(
HttpStatus.CONFLICT.value(),
exception.getMessage(),
LocalDateTime.now()
);
return ResponseEntity.status(HttpStatus.CONFLICT).body(body);
}
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse> handleUserNotFoundException(UserNotFoundException exception) {
ErrorResponse body = new ErrorResponse(
HttpStatus.NOT_FOUND.value(),
exception.getMessage(),
LocalDateTime.now()
);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
}
@ExceptionHandler(NotActiveUserException.class)
public ResponseEntity<ErrorResponse> handleNotActiveUserException(NotActiveUserException exception) {
ErrorResponse body = new ErrorResponse(
HttpStatus.CONFLICT.value(),
"User is blocked or suspended.",
LocalDateTime.now()
);
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
ErrorResponse body = new ErrorResponse(
HttpStatus.BAD_REQUEST.value(),
Objects.requireNonNull(exception.getBindingResult().getFieldError())
.getDefaultMessage(),
LocalDateTime.now()
);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
}
}