英文:
Spring Boot @RestControllerAdvice not Catching Custom Exceptions
问题
@RestControllerAdvice
public class DmsResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
// ... (Validation error handling code)
return ResponseEntity.badRequest().body(response);
}
@ExceptionHandler(PhotoNotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ApiErrorResponse handlePhotoNotFoundException(PhotoNotFoundException ex) {
ApiErrorResponse apiError = new ApiErrorResponse(HttpStatus.NOT_FOUND, 404, ex.getLocalizedMessage(), ex.getMessage());
return apiError;
}
}
@Override
public Resource loadPhotoAsResource(String fileName, Vehicle vehicle, DealerAccount account) throws PhotoNotFoundException {
// ... (Existing code)
Resource resource = optionalResource.orElseThrow(() -> new PhotoNotFoundException("Photo not found!!!"));
if (resource.exists() && resource.isReadable()) {
return resource;
} else {
throw new PhotoNotFoundException("Error retrieving photo!!!");
}
}
@GetMapping("/{fileName:.+}")
public ResponseEntity<?> getPhoto(
@PathVariable String fileName,
@PathVariable Long vehicleId,
@RequestParam("size") String size,
HttpServletRequest request,
@AuthenticationPrincipal DmsUserDetails dmsUser) {
// ... (Existing code)
Resource file = optionalFile.orElseThrow(() -> new PhotoNotFoundException("Photo with filename [" + fileName + "] not found"));
// ... (Content type determination and response setup)
}
Please note that I've removed the HttpStatus
parameter from the handlePhotoNotFoundException
method, which seemed to have resolved your issue. If you need further assistance, feel free to ask.
英文:
I'm using Spring Boot 2.3.1 and I'm having trouble with exceptions. I want to use a @RestControllerAdvice
class to catch exceptions at a global level. I am able to catch validation errors and return a custom error response, but Spring seems to be ignoring my handlePhotoNotFoundException
method. Here is my @RestControllerAdvice
class:
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;
}
}
Here is the method where I am throwing the exception:
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);
}
I am getting the error Error retrieving photo!!!
but with a stacktrace and the 500 error. For some reason, Spring is ignoring my @ExceptionHandler
annotation in the @RestControllerAdvice
class. What I would like to do is quietly log the error, return a message to the user that the image isn't available, then return a URL to a "image is missing" photo.
I'm very new to working with exceptions in Java, so help would be greatly appreciated!
EDIT
Here's the full stack track:
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]
UPDATE
Okay, I removed the HttpStatus
from the method and it works!! Thank you so much for the help!
Now my error response is clean!
答案1
得分: 3
在 Exceptionhandler
方法中:
@ExceptionHandler(PhotoNotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ApiErrorResponse handlePhotoNotFoundException(PhotoNotFoundException ex)
{
ApiErrorResponse apiError = new ApiErrorResponse(HttpStatus.NOT_FOUND, 404, ex.getLocalizedMessage(), ex.getMessage());
return apiError;
}
移除参数 HttpStatus status
,该参数导致了问题。
根据文档,允许的参数有:
> - 异常参数:声明为通用异常或更具体的异常。如果注解本身未通过其 value() 缩小异常类型,则此参数也用作映射提示。
> - 请求和/或响应对象(通常来自Servlet API)。您可以选择任何特定的请求/响应类型,例如 ServletRequest / HttpServletRequest。
> - 会话对象:通常是 HttpSession。这种类型的参数将强制存在相应的会话。因此,这种参数永远不会为空。请注意,会话访问可能不是线程安全的,特别是在Servlet环境中:如果允许多个请求同时访问会话,请考虑将 "synchronizeOnSession" 标志切换为 "true"。
> - WebRequest 或 NativeWebRequest。允许访问通用请求参数以及请求/会话属性访问,而不绑定到本机Servlet API。
> - 当前请求区域设置的区域设置(由最具体的区域设置解析器确定,即Servlet环境中配置的 LocaleResolver)。
> - 用于访问请求内容的 InputStream / Reader。这将是Servlet API公开的原始 InputStream/Reader。
> - 用于生成响应内容的 OutputStream / Writer。这将是Servlet API公开的原始 OutputStream/Writer。
> - Model,作为从处理程序方法返回模型映射的替代方法。请注意,所提供的模型不会预先填充常规模型属性,因此始终为空,这是为了方便为特定于异常的视图准备模型。
英文:
In the Exceptionhandler
method:
@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;
}
The parameter HttpStatus status
is causing the issue. Remove this extra parameter.
From docs, the allowed parameters are:
> - An exception argument: declared as a general Exception or as a more specific exception. This also serves as a mapping hint if the
> annotation itself does not narrow the exception types through its
> value().
> - 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 a
> consequence, such an argument will never be null. Note that session
> access may not be thread-safe, in particular in a Servlet environment:
> Consider switching the "synchronizeOnSession" flag to "true" if
> multiple requests are allowed to access a session concurrently.
> - WebRequest or NativeWebRequest. Allows for generic request parameter access as well as request/session attribute access, without
> ties to the native Servlet API.
> - Locale for the current request locale (determined by the most specific locale resolver available, i.e. the configured LocaleResolver
> in 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 regular
> model attributes and therefore always empty, as a convenience for
> preparing the model for an exception-specific view.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论