gpt4 book ai didi

java - Spring Boot @RestControllerAdvice 没有捕获自定义异常

转载 作者:行者123 更新时间:2023-12-05 03:49:56 28 4
gpt4 key购买 nike

我正在使用 Spring Boot 2.3.1,但遇到异常问题。我想使用 @RestControllerAdvice 类在全局级别捕获异常。我能够捕获验证错误并返回自定义错误响应,但 Spring 似乎忽略了我的 handlePhotoNotFoundException 方法。这是我的 @RestControllerAdvice 类:

DmsResponseEntityExceptionHandler.java

@RestControllerAdvice
public class DmsResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {

ValidationErrorResponse response = new ValidationErrorResponse();
response.setHasErrors(true);

ex.getBindingResult().getAllErrors().forEach(error -> {
ValidationErrorModel errorModel = new ValidationErrorModel();
errorModel.setFieldName(((FieldError) error).getField());
errorModel.setRejectedValue(((FieldError) error).getRejectedValue());
errorModel.setErrorMessage(error.getDefaultMessage());
errorModel.setErrorCode(error.getCode());
response.getErrors().add(errorModel);
});
return ResponseEntity.badRequest().body(response);
}

@ExceptionHandler(PhotoNotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ApiErrorResponse handlePhotoNotFoundException(PhotoNotFoundException ex, HttpStatus status) {

ApiErrorResponse apiError = new ApiErrorResponse(HttpStatus.NOT_FOUND, 404, ex.getLocalizedMessage(), ex.getMessage());

return apiError;
}
}

这是我抛出异常的方法:

PhotoStorageServiceImp.java

@Override
public Resource getThumbnailPhotoByIndex(int index, Vehicle vehicle, DealerAccount account) {
logger.info("LOADING THUMBNAIL!!");
Photo photo = vehicle.getImages().stream().filter(image -> {
return image.getIndexNumber() == index;
}).findFirst().orElseGet(() -> new Photo());

return loadPhotoAsResource(photo.getThumbnailFileName(), vehicle, account);
}

@Override
public Resource loadPhotoAsResource(String fileName, Vehicle vehicle, DealerAccount account) throws PhotoNotFoundException {

logger.info(fileName);
logger.info(account.getId().toString());

initDirectories(vehicle.getId(), account.getId());

Path file = fileUploadDirectory.resolve(fileName).normalize();
logger.info("file " + file.toString());

Optional<Resource> optionalResource = Optional.empty();
try {
optionalResource = Optional.of(new UrlResource(file.toUri()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Resource resource = optionalResource.orElseThrow(() -> new PhotoNotFoundException("Photo not found!!!"));

if(resource.exists() && resource.isReadable()) {
return resource;
} else {
throw new PhotoNotFoundException("Error retrieving photo!!!");
}
}

PhotoUploadController.java

@GetMapping("/{fileName:.+}")
public ResponseEntity<?> getPhoto(
@PathVariable String fileName,
@PathVariable Long vehicleId,
@RequestParam("size") String size,
HttpServletRequest request,
@AuthenticationPrincipal DmsUserDetails dmsUser) {

Vehicle vehicle = vehicleService.findVehicleById(vehicleId);

Optional<Resource> optionalFile = Optional.empty();
Resource resource = null;

switch (size) {
case "thumbnail":
resource = photoUploadService.getThumbnailPhotoByIndex(0, vehicle, dmsUser.getDealerAccount());
break;
case "featured":
optionalFile = photoUploadService.getFeaturedPhotoByIndex(0, vehicle, dmsUser.getDealerAccount());
break;
case "gallery":
optionalFile = photoUploadService.getGalleryPhotoByIndex(0, vehicle, dmsUser.getDealerAccount());
break;
default:

}
logger.info("file resource: " + fileName);



Resource file = optionalFile.orElseThrow(() -> new PhotoNotFoundException("Photo with filename ["+fileName+"] not found"));

// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(file.getFile().getAbsolutePath());
} catch (IOException ex) {
logger.info("Could not determine file type.");
}

// Fallback to the default content type if type could not be determined
if(contentType == null) {
contentType = "application/octet-stream";
}

return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\" + file.getFilename() + \"\\\"")
.contentType(MediaType.parseMediaType(contentType))
.body(file);

我收到错误 Error retrieving photo!!! 但有堆栈跟踪和 500 错误。出于某种原因,Spring 忽略了我在 @RestControllerAdvice 类中的 @ExceptionHandler 注释。我想做的是安静地记录错误,向用户返回一条消息说图像不可用,然后返回一个指向“图像丢失”照片的 URL。

我对在 Java 中处理异常非常陌生,因此非常感谢您的帮助!

编辑

这是完整的堆栈轨道:

com.webbdealer.dms.main.exceptions.PhotoNotFoundException: Error retrieving photo!!!
at com.webbdealer.dms.main.services.PhotoStorageServiceImp.loadPhotoAsResource(PhotoStorageServiceImp.java:177) ~[classes/:na]
at com.webbdealer.dms.main.services.PhotoStorageServiceImp.getThumbnailPhotoByIndex(PhotoStorageServiceImp.java:188) ~[classes/:na]
at com.webbdealer.dms.main.controllers.api.v1.PhotoUploadController.getPhoto(PhotoUploadController.java:120) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:204) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

更新

好的,我从方法中删除了 HttpStatus,它起作用了!!非常感谢您的帮助!

现在我的错误响应是干净的!

Postman Screenshot

最佳答案

Exceptionhandler方法中:


@ExceptionHandler(PhotoNotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ApiErrorResponse handlePhotoNotFoundException(PhotoNotFoundException ex, HttpStatus status)
{
ApiErrorResponse apiError = new ApiErrorResponse(HttpStatus.NOT_FOUND, 404, ex.getLocalizedMessage(), ex.getMessage());

return apiError;
}

参数 HttpStatus status 导致了问题。删除这个额外的参数。

来自 docs ,允许的参数是:

  • An exception argument: declared as a general Exception or as a more specific exception. This also serves as a mapping hint if theannotation itself does not narrow the exception types through itsvalue().
  • Request and/or response objects (typically from the Servlet API). You may choose any specific request/response type, e.g. ServletRequest/ HttpServletRequest.
  • Session object: typically HttpSession. An argument of this type will enforce the presence of a corresponding session. As aconsequence, such an argument will never be null. Note that sessionaccess may not be thread-safe, in particular in a Servlet environment:Consider switching the "synchronizeOnSession" flag to "true" ifmultiple requests are allowed to access a session concurrently.
  • WebRequest or NativeWebRequest. Allows for generic request parameter access as well as request/session attribute access, withoutties to the native Servlet API.
  • Locale for the current request locale (determined by the most specific locale resolver available, i.e. the configured LocaleResolverin a Servlet environment).
  • InputStream / Reader for access to the request's content. This will be the raw InputStream/Reader as exposed by the Servlet API.
  • OutputStream / Writer for generating the response's content. This will be the raw OutputStream/Writer as exposed by the Servlet API.
  • Model as an alternative to returning a model map from the handler method. Note that the provided model is not pre-populated with regularmodel attributes and therefore always empty, as a convenience forpreparing the model for an exception-specific view.

关于java - Spring Boot @RestControllerAdvice 没有捕获自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63697260/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com