Exception handling for RESTful service in Spring framework

In last couple of posts we have seen how to create RESTful service using Spring framework. Here we will see how can we handle error conditions and return appropriate status code and message.

  • Use @ResponseStatus on custom exception

In case of error, throw custom exception annotate with @ResponseStatus. Code below shows how to define CustomException. 

@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE, reason = "The service is unavailable")
class CustomException extends RuntimeException{

  • Return ResponseEntity<> with appropriate error code

ResponseEntity can be used as below.

public class HelloController {
    public ResponseEntity sayHello(@RequestParam(value="name", required = false, defaultValue = "World") String name) {
        try {
            return new ResponseEntity<>(String.format("Hello %s with Spring Boot !!!", name), HttpStatus.OK);
        }catch (RuntimeException excp){
            //log error excp
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

  • You also throw RuntimeException which will return with error code "Internal Server Error" always. 


Popular posts from this blog

Error : login failed on rabbitmq web-management console

MSMQ error : "A workgroup installation computer does not support the operation."

How to flash CWM Recovery to Samsung Galaxy SL( GT-I9003) using Odin