globalExceptionHandler hinzugefügt
der Advice fängt aufgetretene Fehler ab und gibt dann ein ResponseEntity zurück mit den vorher definierten Exceptions, zusätzlich werden alle nicht aufgeführten exceptions mit handleAll ebenfalls abgefangen um kein Stacktrace zu leaken
This commit is contained in:
1 parent
aa6b5c7444
commit
292c1922dd
1 file changed
+39
@@ -0,0 +1,39 @@
|
||||
package de.timaldinger.einkaufsliste.Exceptions;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.context.request.ServletWebRequest;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
|
||||
@ExceptionHandler(BadRequestException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBadRequest(BadRequestException e, HttpServletRequest req) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(new ErrorResponse(400, e.getMessage(), req.getRequestURI()));
|
||||
}
|
||||
@ExceptionHandler(ResourceNotFoundException.class)
|
||||
public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException e, HttpServletRequest req) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(new ErrorResponse(404, e.getMessage(), req.getRequestURI()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleAll(Exception e, HttpServletRequest req){
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ErrorResponse(500,"Internal error", req.getRequestURI()));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected @Nullable ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatusCode statusCode, WebRequest request) {
|
||||
var error = new ErrorResponse(statusCode.value(), ex.getMessage(),((ServletWebRequest) request).getRequest().getRequestURI());
|
||||
return new ResponseEntity<>(error,headers,statusCode);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user