its done like this, Declare GlobalExceptionHandler with ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(KeyNotFoundException.class)
public ResponseEntity<ExceptionResponse> keyNotFound(KeyNotFoundException ex) {
ExceptionResponse response = new ExceptionResponse();
response.setStatusCode(HttpStatus.BAD_REQUEST.toString().substring(0,3));
response.setError(HttpStatus.BAD_REQUEST.getReasonPhrase());
response.setMessage(ex.getMessage());
response.setTimestamp(LocalDateTime.now());
return new ResponseEntity<ExceptionResponse>(response, HttpStatus.BAD_REQUEST);
}
}
KeyNotFoundException
public class KeyNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public KeyNotFoundException(String message) {
super(message);
}
}
ExceptionResponse
public class ExceptionResponse {
private String error;
private String message;
private String statusCode;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private LocalDateTime timestamp;
// getters and setters
in api code catch block where you find parameter is missing or key is missing from request
throw new KeyNotFoundException ("Key not found in the request..."+ex.getMessage());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…