- 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 ResponseEntitysayHello(@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