spring自定义异常处理
在控制层对异常进行处理,确保异常堆栈信息不返回前端使用者.
1.在web.xml配置errorcode,只能用在同步开发中.
<error-page>
<error-code>500</error-code>
<location>/page/error.html</location>
</error-page>
2.局部异常处理
//对当前处理器类中的所有方法的异常进行处理
@ExceptionHandler(Exception.class)
public AjaxResult doException(Exception e){
//服务器出异常,能做什么,把异常记录到文件
System.out.println(e.getMessage());
return AjaxResult.error(MvcStatus.EXCEPTION);
}
3.全局异常处理
@Component
public class MyExceptionHanler implements HandlerExceptionResolver {
//这个异常处理方法,既能处理同步(能够返回错误页面),也能处理异步(返回json数据)
@Override
public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object o, Exception e) {
HandlerMethod m = (HandlerMethod) o;
System.out.println(e.getMessage());
try {
PrintWriter writer = resp.getWriter();
writer.print(JSON.toJSONString(new AjaxResult(MvcStatus.EXCEPTION)));
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
}
优点:全局处理,对所有处理器都有效
缺点:返回的异常信息太单一,做不到针对不同服务器异常返回个性化信息.
4.全局统一异常处理(重要,推荐使用)
@RestControllerAdvice
public class GlobExceptionHandler {
@ExceptionHandler(Exception.class)
public AjaxResult doException(Exception e){
//TODO 记录异常
System.out.println("-----"+e.getMessage());
return AjaxResult.error(MvcStatus.EXCEPTION);
}
@ExceptionHandler(MvcException.class)
public AjaxResult doMvcException(MvcException e){
//TODO 记录异常
System.out.println(e.getS().getMsg()+"--"+e.getS().getCode());
return AjaxResult.error(e.getS());
}
}

浙公网安备 33010602011771号