1
我有一个自定义异常类定义为自定义异常没有与处理@ExceptionHandler标注的方法
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
注释如下
@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
}
如何解决与自定义异常问题?
[为什么Catch(Exception)几乎总是一个坏主意?](http://stackoverflow.com/questions/2416316/why-is-the-catchexception-almost-always-a-bad-理念) – Raedwald