In my spring boot rest api app,I want to define a automatic method for unhandled exception.Suppose client give wrong password in login endpoint.The response is 403 forbidden without any message.but i want to give some message as a response and want to give all the unhandled exception to this same format of message. I try this:
@ResponseStatus
@ControllerAdvice
public class RestErrorResponse extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorMessage> handleServerError(Exception exception){
ErrorMessage message = new ErrorMessage(
"Failed",
exception.getMessage(),
400
);
return ResponseEntity.status(400).body(message);
}
}
The ErrorMessage class
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ErrorMessage {
private String status;
private String message;
private Integer statusCode;
}
This is work.But the problem is i need to define the code itself.Here the code is 400.But i don't know which exception is happened.I need the status code daynamically anyhow. Find a answer in stackoverflow and i also try this below code
@ResponseStatus
@ControllerAdvice
public class RestErrorResponse extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorMessage> handleServerError(Exception exception,HttpServletResponse response){
ErrorMessage message = new ErrorMessage(
"Failed",
exception.getMessage(),
response.getStatus()
);
return ResponseEntity.status(response.getStatus()).body(message);
}
}
But the response.getStatus() always return 200.
@ExceptionHandler(MyException.class)annotation.