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

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...