Spring Boot Exception Handling — ResponseStatusException

Error and Exception handling is essential for a web application and proper responses with reasonable details are required for better debugging and user experience. Spring Boot provides a /error mapping that handles all errors in a sensible way, and it is registered as a “global” error page in the servlet container. If you are implementing a rest API or a web application with a UI template you will get a proper JSON or HTML view rendered. You will have the option to change this template using different methods.

There are different techniques to handle exceptions at the controller level as well as application level. Using these methods you are able to prepare the proper response with the proper status.

In this article, we will focus on ResponseStatusException and share some examples with this class to handle exceptions for web applications.

Getting Started

One of the easiest ways to handle application exceptions is to use ResponseStatusException and it is available on Spring 5 and above. But this simplicity also comes with some drawbacks also which we will mention after the example.

Basically what you need to do is to catch the application exception and throw a ResponseStatusException instead with preferred input like the response code and message.

@RestController
@RequestMapping("/api/v1/")
public class StudentRestController {

@Autowired
StudentService studentService;

@GetMapping("student/{id}")
public ResponseEntity<Student> getUser(
@PathVariable(name = "id", required = false) Long id ) {
Student student;
try {
student = studentService.findStudentById(null);
} catch (InvalidIdException e) {
e.printStackTrace();
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, e.getMessage(), e);
} catch (ServiceDownTimeException e) {
e.printStackTrace();
throw new ResponseStatusException(
HttpStatus.SERVICE_UNAVAILABLE, e.getMessage(), e);
}
return ResponseEntity
.status(HttpStatus.OK)
.body(student);
}

}

This exception can even be used at the service level and that approach can help you in terms of the number of exceptions you are creating. But as you can probably guess by now it is not a good solution for unified exception handling compared to ControllerAdvice or HandlerExceptionResolver.

For example, in the case of ResponseStatusException you will get the following response.

{
"timestamp": "2022-05-20T19:17:54.442+00:00",
"status": 503,
"error": "Service Unavailable",
"message": "1-2 AM is service downtime!",
"path": "/api/v1/student/1"
}

The Example code is available on GitHub. You can learn more about the other methods of handling exceptions in the following articles:

Hope this article helped you and please support me with your applauding 👏 for the story. if you don’t know how it is just like this:

Or buy me a coffee here!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Farzin Pashaee

Farzin Pashaee

Software Engineer at Maybank, AI and ML enthusiastic