diff options
| author | Kevin J Hoerr <khoerr@ksmpartners.com> | 2022-01-27 14:12:29 -0500 |
|---|---|---|
| committer | Kevin J Hoerr <khoerr@ksmpartners.com> | 2022-01-27 14:12:29 -0500 |
| commit | 615c8a0fc8d2b35da7df90115456d33444104c41 (patch) | |
| tree | aeab4261b4edaf63905bd008ce6992b0d2490916 /src/main/java/dev/submelon/pantry/CustomControllerAdvice.java | |
| parent | 8d8d8cdd639591c0c4c49b355db1152e310c22d6 (diff) | |
| download | pantry-615c8a0fc8d2b35da7df90115456d33444104c41.tar.gz pantry-615c8a0fc8d2b35da7df90115456d33444104c41.tar.bz2 pantry-615c8a0fc8d2b35da7df90115456d33444104c41.zip | |
Add error handling
Diffstat (limited to 'src/main/java/dev/submelon/pantry/CustomControllerAdvice.java')
| -rw-r--r-- | src/main/java/dev/submelon/pantry/CustomControllerAdvice.java | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/main/java/dev/submelon/pantry/CustomControllerAdvice.java b/src/main/java/dev/submelon/pantry/CustomControllerAdvice.java new file mode 100644 index 0000000..dad961b --- /dev/null +++ b/src/main/java/dev/submelon/pantry/CustomControllerAdvice.java @@ -0,0 +1,46 @@ +package dev.submelon.pantry; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.NoSuchElementException; + +@ControllerAdvice +class CustomControllerAdvice { + @ExceptionHandler(NoSuchElementException.class) + public ResponseEntity<ErrorResponse> handleNullPointerExceptions( + NoSuchElementException e + ) { + HttpStatus status = HttpStatus.NOT_FOUND; + + return new ResponseEntity<>( + new ErrorResponse(status, e.getMessage()), + status + ); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity<ErrorResponse> handleExceptions( + Exception e + ) { + HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; + + // converting the stack trace to String + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + e.printStackTrace(printWriter); + String stackTrace = stringWriter.toString(); + + return new ResponseEntity<>( + new ErrorResponse( + status, + e.getMessage(), + stackTrace // specifying the stack trace in case of 500s + ), + status + ); + } +} |
