Java 未使用@ExceptionHandler注释的方法处理自定义异常
我有一个自定义异常类,定义为Java 未使用@ExceptionHandler注释的方法处理自定义异常,java,spring,spring-mvc,Java,Spring,Spring Mvc,我有一个自定义异常类,定义为 public class CustomAuthenticationException extends RuntimeException{ } 从一个控制器方法中,我抛出这个异常,如下所示 @RequestMapping(value="/tasks", method=RequestMethod.GET) public String loadTasks(HttpServletRequest request){ try
public class CustomAuthenticationException extends RuntimeException{
}
从一个控制器方法中,我抛出这个异常,如下所示
@RequestMapping(value="/tasks", method=RequestMethod.GET)
public String loadTasks(HttpServletRequest request){
try
{
if (!isAuthenticatedRequest(request))
{
throw new CustomAuthenticationException();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return "tasks/tasks";
}
@ExceptionHandler(CustomAuthenticationException.class)
public void handleCustomException(CustomAuthenticationException ex){
//method is not getting invoked
}
为了从该控制器的作用域捕获此异常,我定义了一个带有@ExceptionHandler
注释的方法,如下所示
@RequestMapping(value="/tasks", method=RequestMethod.GET)
public String loadTasks(HttpServletRequest request){
try
{
if (!isAuthenticatedRequest(request))
{
throw new CustomAuthenticationException();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return "tasks/tasks";
}
@ExceptionHandler(CustomAuthenticationException.class)
public void handleCustomException(CustomAuthenticationException ex){
//method is not getting invoked
}
当我启动GET请求并期望由上述方法处理异常时,我只在控制台中获得错误堆栈跟踪。永远不会调用异常处理程序方法
但是,对于其他定义的异常,如MethodArgumentNotValidException
,处理程序方法被正确调用。例如,我使用了以下异常处理程序:
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ErrorResponseHolder handleFieldValidationError(MethodArgumentNotValidException ex, HttpServletResponse response){
//method got invoked. do something with the exception
}
如何解决自定义异常的问题?异常处理不正确,在方法loadTasks中,您正在抛出异常并捕获异常,因此它不会传播 若您想要处理未处理的异常,例如泛型异常(Exception.class),那个么您需要编写一个方法,该方法应该在公共异常处理类中处理所有这些异常
@ExceptionHandler(Exception.class)
public void handleUnhandledException(Exception ex){
// handle the exception here
}
一旦抛出异常,永远不要用相同的方法捕获异常,在发送正确响应的位置捕获异常。可能重复的