我使用@ControllerAdvice
来处理我应用程序的所有异常:
我使用@ControllerAdvice
来处理我应用程序的所有异常:
@ControllerAdvice
public class ExceptionHandlingController {
@ExceptionHandler({UnauthorizedException.class})
public String unauthorizedException() {
.........
}
@ExceptionHandler({UnauthorizedAjaxException.class})
@ResponseBody
public void unauthorizedAjaxException() {
.........
}
@ExceptionHandler({Exception.class})
public String globalException(){
.........
}
}
在我的代码中某个地方,我会执行 throw new UnauthorizedException();
@Around("@annotation(Authenticated)")
public Object profilingAuthentication(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
if( request.getSession().getAttribute("idContact") == null ) {
if( "XMLHttpRequest".equals(request.getHeader("X-Requested-With")) )
throw new UnauthorizedAjaxException();
throw new UnauthorizedException();
}
return pjp.proceed();
}
不幸的是,Spring MVC 似乎会随机使用最常见的情况(Exception
),而不是更具体的情况(例如UnauthorizedException
)。有时他会选择正确的情况!
顺序是如何工作的?是否有任何指定顺序的方法?
UnauthorizedException
是一个自定义异常
public class UnauthorizedException extends Exception {
public UnauthorizedException(){
super();
}
public UnauthorizedException(String message){
super(message);
}
}
更新
我发现订单实际上不是随机的,抛出UnauthorizedException
异常的方法确实正常工作,但其他方法则不是!
@Authenticated
@RequestMapping(value="/favoris")
public String favoris(ModelMap model, HttpServletRequest request)
throws UnauthorizedException {
....
}
@Authenticated
@RequestMapping(value="/follow")
public String follow(ModelMap model, HttpServletRequest request) {
.....
}
那么我必须手动添加 throws UnauthorizedException
还是有其他解决方案?
UnauthorizedException
的方法它不起作用时,这是什么意思?由于UnauthorizedException
是自定义异常,你必须抛出它,否则应用程序如何为你抛出它呢? - Vinu Dominic