Created
June 28, 2016 20:49
-
-
Save m-x-k/c68b0bdf4696ee8c0b4a78aef8175ea0 to your computer and use it in GitHub Desktop.
Spring Rest Exception Handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
compile('org.springframework.boot:spring-boot-starter-web') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyRestException extends RuntimeException { | |
public MyRestException(String s) { | |
super(s); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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