-
出现异常现象的常见位置与常见诱因如下:
-
框架内部抛出异常:因使用不和规则导致
-
数据层抛出异常:因外部服务器故障导致(例如:服务器访问超时)
-
业务层抛出异常:因业务逻辑书写错误导致(遍历业务书写操作,导致索引异常等)
-
表现层抛出异常:因数据收集,校验等股则导致(不匹配的数据类型间导致异常)
-
工具类抛出异常:因工具类书写不够严谨不够健壮导致(必要释放的连接长期未释放)
-
-
各个层均抛出异常,异常处理代码书写在哪一层?
-
所有的异常均抛出到表现层进行统一处理。
-
-
表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强,如何解决——AOP思想
项目异常处理方案
-
项目异常分类
-
业务异常(BusinessException)
1. 规范的用户行为产生的异常
-
不规范的用户行为操作产生的异常
-
*发送对应的消息传递给用户,提醒规范操作
-
-
系统异常(SystemException)
-
项目运行过程中可预计且无法避免的异常
-
*发送固定的消息传递给用户,安抚用户
*发送特定消息给运维人员,提醒维护
*记录日志
-
-
其它异常(Exception)
-
编程人未预期到的异常
-
**发送固定的消息传递给用户,安抚用户
*发送特定消息给编程人员,提醒维护(纳入预期范围)
*记录日志
-
-
Exception
-
SystemException
package com.yang.exception;
public class SystemException extends RuntimeException{
private Integer code;
public SystemException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public SystemException(Integer code, String message) {
super(message);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
-
BusinessException
package com.yang.exception;
public class BusinessException extends RuntimeException{
private Integer code;
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
-
service【造的异常】
-
Controller :ProjectExceptionAdvice
package com.yang.controller;
import com.yang.exception.BusinessException;
import com.yang.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
-
Code
package com.yang.controller;
public class Code {
public static final Integer SYSTEM_UNKNOWN_ERROR = 50001;
public static final Integer SYSTEM_TIMEOUT_ERROR = 50002;
public static final Integer PROJECT_VALIDATE_ERROR = 60001;
public static final Integer PROJECT_BUSINESS_ERROR = 60002;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码