Lets directly see a demo to understand exception handling in Springboot better.
Suppose I have the below api endpoint:
@GetMapping("/test") public String test() { return "Working fine"; }
Obviously the above endpoint will work fine if you call this URL: http://localhost:8080/test
But you will get something like below if you call this URL : http://localhost:8080/some-nonexist-url
It is a good response, you are getting enough information. So, Springboot takes care of these kind of errors.
Now, lets throw an exception and see how Spring boot handles it.
@GetMapping("/test") public String test() { if(true) throw new MyException("My exception message"); return "Working fine"; }
And the MyException class looks like this:
public class MyException extends RuntimeException{ public MyException(String exception) { super(exception); } }
Now if you call the same url : http://localhost:8080/test, below would be the output:
You can see you are getting a generic exception, if you want to make it throw some specific exception you can mention the below annotation on top of MyException class:
@ResponseStatus(HttpStatus.NOT_FOUND)
And then when you hit the same URL again you will see below error:
So by the above way you are customizing the return status for a specific exception.
Lets see now how you can customize the response structure of the exception.
First create the POJO MyExceptionDetails.java class:
public class MyExceptionDetails { private Date timestamp; private String message; private String details; public MyExceptionDetails(Date timestamp, String message, String details) { super(); this.timestamp = timestamp; this.message = message; this.details = details; } //Add only setters. }
Then have another class where you define your @ControllerAdvice:
@ControllerAdvice @RestController public class MyCustomizedExceptionHandler extends ResponseEntityExceptionHandler{ @ExceptionHandler(MyException.class) public final ResponseEntity<MyExceptionDetails> handleUserNotFoundException(MyException ex, WebRequest request) { MyExceptionDetails errorDetails = new MyExceptionDetails(new Date(), ex.getMessage(), request.getDescription(false)); return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND); } }
Now if you call the same URL you will get the exception message in your format: