1.主观题 (50分) 说明Spring Boot应用异常统一处理的3种方式
时间: 2024-02-06 22:13:11 浏览: 24
在Spring Boot应用程序中,异常统一处理是一个非常重要的功能,能够提高应用程序的稳定性和可靠性。Spring Boot提供了多种方式来实现异常统一处理,常见的有以下三种方式:
1. 使用@ControllerAdvice注解和@ExceptionHandler注解实现全局异常统一处理:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception e) {
ModelAndView mv = new ModelAndView();
mv.addObject("message", e.getMessage());
mv.setViewName("error");
return mv;
}
}
在全局异常处理类中,使用@ExceptionHandler注解处理指定的异常类型,当应用程序中出现该异常时,会调用对应的处理方法进行处理。
2. 实现ErrorController接口实现全局异常统一处理:
@Controller
public class GlobalErrorController implements ErrorController {
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping(value = "/error")
public ModelAndView handleError(HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
mv.addObject("status", request.getAttribute("javax.servlet.error.status_code"));
mv.addObject("message", request.getAttribute("javax.servlet.error.message"));
mv.addObject("exception", request.getAttribute("javax.servlet.error.exception"));
mv.setViewName("error");
return mv;
}
}
实现ErrorController接口,重写getErrorPath方法和handleError方法,通过request对象获取异常信息并进行处理。
3. 使用Spring Boot提供的ErrorAttributes接口实现全局异常统一处理:
@RestController
public class GlobalErrorController implements ErrorController {
@Autowired
private ErrorAttributes errorAttributes;
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping(value = "/error")
public Map<String, Object> handleError(HttpServletRequest request) {
Map<String, Object> errorMap = errorAttributes.getErrorAttributes(new ServletWebRequest(request), false);
return errorMap;
}
}
使用@Autowired注解注入ErrorAttributes对象,在全局异常处理方法中,通过errorAttributes对象获取异常信息并进行处理。
以上是Spring Boot应用异常统一处理的三种方式,开发者可以根据自己的实际需求选择不同的方式。