我正在编写一个Spring Boot应用程序,在我的一个控制器中,我有以下映射:
@PostMapping("/")
public String doSomething( )
{
Foo bar = new Foo();
bar.doSomething();
return "/Complete";
}
还有一个异常处理类中映射的另一个映射:
@PostMapping("/error")
public ModelAndView doSomething( String error )
{
// Handle error here..
}
所以在类栏哪个不是控制器有一种方法可以重定向到/错误映射传递错误..我问这个因为它节省了我不得不经常抛出异常通话栈/可以捕获所有内容!
由于
答案 0 :(得分:0)
第一种方法:
一个解决方案是使用@ExceptionHandler
注释。
例如:
@PostMapping("/")
public String doSomething( )
{
Foo bar = new Foo();
bar.doSomething();
throw new RuntimeException("Hello Exception");
return "/Complete";
}
@ExceptionHandler(Exception.class)
public String doSomething( String error )
{
// Handle error here and return error view..
return "error_view";
}
在上面的示例中,每次从包含@ExceptionHandler
处理程序的控制器作用域抛出异常时,将调用此处理程序,并使用它来决定将呈现哪个视图。
此解决方案仅限于一个控制器范围,即保留@ExceptionHandler
处理程序的范围。
第二种方法:
使用全局处理程序异常解析程序,您需要添加一个实现HandlerExceptionResolver
接口的类。
例如:
@Component
public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception exception
) {
// return here your global exception view
return null;
}
}
将该处理程序标记为Spring Bean
非常重要第三种方法:
使用控制器建议,但是,我相信第二种方法更符合您的需求。