问题描述
浏览几天后我没有找到解决方案,所以我想我会发帖。 马上,对不起我的英语。
我正在尝试从使用 Jhipster 的技术堆栈(Spring MVC、JPA 等)在 Java 中运行的后端获取自定义异常到我的前端。在某些情况下,我创建了自定义异常,并使用我在 Jhipster 生成的 ControllerAdvice 中添加的自定义处理程序处理它,一切正常。
在另一种情况下,我试图捕获相同的异常,但 ControllerAdvice 根本没有触发,最终我遇到了一个错误,我无法在前端做任何事情。使用 Jhipster 生成的异常,我得到了同样的无法使用的错误。
controllerAdvice(由 jhipster 生成)
@ControllerAdvice
public class ExceptionTranslator implements ProblemHandling,SecurityAdviceTrait {
private static final String FIELD_ERRORS_KEY = "fieldErrors";
private static final String MESSAGE_KEY = "message";
private static final String PATH_KEY = "path";
private static final String VIOLATIONS_KEY = "violations";
@Value("${jhipster.clientApp.name}")
private String applicationName;
......
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(odoLoginAlreadyUsedException.class)
protected ResponseEntity<Object> handleLoginAlreadyUsed(odoLoginAlreadyUsedException ex,NativeWebRequest request){
ApiError apiError = new ApiError(HttpStatus.CONFLICT);
apiError.setMessage(ex.getMessage());
return buildresponseEntity(apiError,request);
}
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(odoEmailAlreadyUsedException.class)
protected ResponseEntity<Object> handleEmailAlreadyUsed(odoEmailAlreadyUsedException ex,request);
}
private ResponseEntity<Object> buildresponseEntity(ApiError apiError,NativeWebRequest request) {
return new ResponseEntity<>(apiError,apiError.getStatus());
}
异常示例
public class odoLoginAlreadyUsedException extends RuntimeException{
public odoLoginAlreadyUsedException(){
super("Ce pseudo est déjà utilisé,veuillez ré-éssayer avec un pseudo différent.");
}
}
有效:
RestController
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<AdvisorVM> registeraccount(@Valid @RequestBody AdvisorIn advisorIn) {
if (!checkPasswordLength(advisorIn.getpassword())) {
throw new InvalidPasswordException();
}
advisorIn.setCreatedBy("Platform_Advisor");
advisorIn.setCreatedDate(Instant.Now());
User user = userService.registerUser(advisorIn,advisorIn.getpassword()); ....
服务
public User registerUser(UserDTO userDTO,String password){
userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).ifPresent(existingUser -> {
boolean removed = removeNonActivatedUser(existingUser);
if (!removed) {
throw new odoLoginAlreadyUsedException();
}
});
userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).ifPresent(existingUser -> {
boolean removed = removeNonActivatedUser(existingUser);
if (!removed) {
throw new odoEmailAlreadyUsedException();
}
});
User newUser = new User();
有了这个,我的 ControllerAdvice 捕获了异常,用我试图获取的状态和错误消息构建一个响应
这不会
RestController
@PostMapping("/actions/ceUser")
@PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")" + " ||hasRole(\"" + AuthoritiesConstants.ROLE_MANAGER + "\")")
public @ResponseBody
ResponseEntity<String> createEditUser(@Valid @RequestBody CEUser ceUser) throws URISyntaxException,JsonParseException,JsonMappingException,IOException {
User loggedUser = userService.getUserWithAuthorities().get();
var userExtraGlobal=userExtraCustomService.findByUser(loggedUser).get();
// User id is provided or not
boolean createuser = (ceUser.getId() == null);
if (createuser) log.debug("REST request to create User : {}",ceUser);
else log.debug("REST request to update User : {}",ceUser.getFirstName() + " " + ceUser.getLastName());
if (ceUser.getLogin() == null || ceUser.getLogin().isBlank()) {
throw new RuntimeException("User login should not be null or blank");
}
if (createuser){
if(userService.findOneByLogin(ceUser.getLogin().toLowerCase()).isPresent()) {
throw new odoLoginAlreadyUsedException();
} if(userService.findOneByEmail(ceUser.getEmail()).isPresent()) {
throw new odoEmailAlreadyUsedException();
}
}
堆栈跟踪
2021-03-15 12:02:37.593 ERROR 25372 --- [ XNIO-1 task-28] c.odonatech.odo360.web.rest.odoResource : Exception in createEditUser() with cause = 'NULL' and exception = 'Login name already used!'
com.odonatech.odo360.web.rest.errors.LoginAlreadyUsedException: Login name already used!
at com.odonatech.odo360.web.rest.odoResource.createEditUser(odoResource.java:185)
at com.odonatech.odo360.web.rest.odoResource$$FastClassBySpringcglib$$2e8c9e4b.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.cglibAopProxy$cglibMethodInvocation.invokeJoinpoint(cglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.cglibAopProxy$cglibMethodInvocation.proceed(cglibAopProxy.java:749)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.cglibAopProxy$cglibMethodInvocation.proceed(cglibAopProxy.java:749)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:69)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.cglibAopProxy$cglibMethodInvocation.proceed(cglibAopProxy.java:749)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.cglibAopProxy$cglibMethodInvocation.proceed(cglibAopProxy.java:749)
at org.springframework.aop.framework.cglibAopProxy$DynamicAdvisedInterceptor.intercept(cglibAopProxy.java:691)
at com.odonatech.odo360.web.rest.odoResource$$EnhancerBySpringcglib$$97daf673.createEditUser(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.invocableHandlerMethod.doInvoke(invocableHandlerMethod.java:190)
at org.springframework.web.method.support.invocableHandlerMethod.invokeForRequest(invocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletinvocableHandlerMethod.invokeAndHandle(ServletinvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.dispatcherServlet.dodispatch(dispatcherServlet.java:1040)
at org.springframework.web.servlet.dispatcherServlet.doService(dispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:523)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:155)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at com.odonatech.odo360.security.jwt.JWTFilter.doFilter(JWTFilter.java:38)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.logoutFilter.doFilter(logoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcmetricsFilter.doFilterInternal(WebMvcmetricsFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at io.undertow.servlet.handlers.ServletdispatchingHandler.handleRequest(ServletdispatchingHandler.java:36)
at io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
at io.undertow.servlet.handlers.security.SSLinformationAssociationHandler.handleRequest(SSLinformationAssociationHandler.java:132)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.SessionRestoringHandler.handleRequest(SessionRestoringHandler.java:119)
at io.undertow.servlet.handlers.ServletinitialHandler.handleFirstRequest(ServletinitialHandler.java:269)
at io.undertow.servlet.handlers.ServletinitialHandler.access$100(ServletinitialHandler.java:78)
at io.undertow.servlet.handlers.ServletinitialHandler$2.call(ServletinitialHandler.java:133)
at io.undertow.servlet.handlers.ServletinitialHandler$2.call(ServletinitialHandler.java:130)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.handlers.ServletinitialHandler.dispatchRequest(ServletinitialHandler.java:249)
at io.undertow.servlet.handlers.ServletinitialHandler.access$000(ServletinitialHandler.java:78)
at io.undertow.servlet.handlers.ServletinitialHandler$1.handleRequest(ServletinitialHandler.java:99)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:835)
2021-03-15 12:02:37.602 WARN 25372 --- [ XNIO-1 task-28] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [https://www.jhipster.tech/problem/login-already-used{400,Login name already used!,message=error.userexists,params=userManagement}]
使用我的自定义异常或 Jhipster 的内置异常,我在前端获得 500 状态,并带有不可解析的 json 响应,但我无能为力。
我尝试从我的服务而不是我的 RestController 中抛出我的异常。我尝试了不同的注释(例如EnableMVC)和其他我读过的东西,但我无法确定为什么它在两种情况下的响应不同。 我阅读了有关过滤器的内容,可能会妨碍 ControllerAdvice?我不知道,如果你们能指导我朝着正确的方向前进!
提前致谢
编辑
资源中有一个异常处理程序捕获所有运行时异常(我的自定义异常扩展了它),所以它没有被分派到 ControllerAdvice... ...无论如何,谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)