Web 应用程序中全局业务异常
2021-07-02 本文已影响0人
南湘嘉荣
对于所有的web应用来说,业务异常是程序开发中经常要遇到的,比如不满足某个条件,业务就不允许往下走。
而这些业务逻辑的处理一般都应是放在Service层处理的,而业务异常也应该由Service层抛出。最后,统一在控制层进行异常处理。这样做的好处就是可以在将错误信息一起打包返回给前端。
下面是个人设计的一个全局业务异常类。
package com.sensible.exception;
import com.sensible.api.enu.IReturnCode;
/**
* @author liuyc
* @Description: 通用业务异常类
* @date 2021-7-2 20:30:58
*/
public class BusinessException extends RuntimeException{
private IReturnCode errorCode;
public BusinessException(IReturnCode code) {
super(code.getMessage());
this.errorCode = code;
}
public BusinessException(String message) {
super(message);
}
public BusinessException(String message, IReturnCode errorCode) {
super(message);
this.errorCode = errorCode;
}
public BusinessException(String message, Throwable cause, IReturnCode errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
public IReturnCode getErrorCode() {
return errorCode;
}
}