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.


@RestController
public class HelloController {
    @RequestMapping("/hello")
    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. 

Comments

Popular posts from this blog

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

How to boot Samsung Galaxy SL( GT-I9003) in recovery mode

Exception handling with RestTemplate