Skip to content

Instantly share code, notes, and snippets.

@m-x-k
Created June 28, 2016 20:49
Show Gist options
  • Save m-x-k/c68b0bdf4696ee8c0b4a78aef8175ea0 to your computer and use it in GitHub Desktop.
Save m-x-k/c68b0bdf4696ee8c0b4a78aef8175ea0 to your computer and use it in GitHub Desktop.
Spring Rest Exception Handling
compile('org.springframework.boot:spring-boot-starter-web')
@RestController
public class GreetingController {
@RequestMapping("/my/rest/exception")
public @ResponseBody ResponseEntity<String> myException() {
if (true)
throw new MyRestException("should see me");
return new ResponseEntity<String>("don't see me", HttpStatus.OK);
}
}
public class MyRestException extends RuntimeException {
public MyRestException(String s) {
super(s);
}
}
@ControllerAdvice
public class MyRestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {MyRestException.class})
protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest webRequest) {
String bodyOfResponse = "Well that's another fine mess you got me into";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, webRequest);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment