0

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.

2
  • You can handle specific exceptions in separate methods using @ExceptionHandler(MyException.class) annotation. Commented Aug 17, 2023 at 21:51
  • You don't get my point?I want daynamic exception handler for all unhandeled exception so that i can send back a same formatted message to client Commented Aug 18, 2023 at 4:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.