|
|
|
@@ -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);
|
|
|
|
|
}
|
|
|
|
|
}
|