1.各个层级均出现异常,异常处理代码书写在哪一层?
所有的异常均抛出到表现层进行处理
2.表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强,如何解决?
AOP思想
在Spring MVC框架中,异常处理器(Exception Handler)用于捕获和处理控制器(Controller)层中发生的异常。Spring MVC提供了多种方式来实现异常处理。
异常处理器写在表现层:例如
@RestControllerAdvice
public class GlobalRestExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse("An error occurred: " + ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
项目异常分类
-
业务异常 (BusinessException):规范的用户行为产生的异常、不规范的用户行为操作产生的异常
-
系统异常(SystemException):项目运行过程中可预计且无法避免的异常
-
其他异常 (Exception):编程人员未预期到的异常
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex) {
//记录日志
//发送消息给运维
//发送消息给开发人员
return new Result(null, ex.getCode(), ex.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex) {
return new Result(null, ex.getCode(), ex.getMessage());
}
@ExceptionHandler(Exception.class)
public Result doException(Exception ex) {
//记录日志
//发送消息给运维
//发送消息给开发人员
return new Result(null, Code.SYSTEM_UNKNOW_ERR, "系统繁忙,稍后再试");
}
}
页面放行:使用webmvcconfiger接口,复写addresourcehandlers方法
@Configuration
public class SpringMvcSupport implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
}