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. 

No comments:

Post a Comment

Caching is a technique used to store frequently accessed data in a temporary storage layer to improve system performance and reduce latency....