9-springboot统一异常处理

发布时间 2023-03-22 21:16:26作者: companion

500错误页面之前可以xml中配置errorpage的配置,或者tomcat的web.xml中处理,现在可以进行统一处理。

新建处理类统一处理

@ControllerAdvice
public class ExceptionHandler {
@org.springframework.web.bind.annotation.ExceptionHandler(value = RuntimeException.class)
public @ResponseBody Object errorHandlerByJson(HttpServletRequest request,Exception e) throws Exception{
//可以拿到异常信息
e.printStackTrace();
//可以返回统一数据
return "服务器开小差";
}
或者如果返回其他格式的话,例如modelandview 需要把上面的value相同的注释掉
@org.springframework.web.bind.annotation.ExceptionHandler(value = RuntimeException.class)
public ModelAndView errorHandlerByView(HttpServletRequest request, Exception e) throws Exception{
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception",e.getMessage());
modelAndView.addObject("url",request.getRequestURL());
modelAndView.setViewName("50x");
//可以返回统一数据
return modelAndView;
}
}

@Controller
public class ExceptionController {
@RequestMapping("/hello")
public @ResponseBody String hello(){
int i = 10/0;
return "hello join";
}
}