SpringMvc---ssm整合--异常处理器(5)

SpringMvc---ssm整合--异常处理器(5),第1张

出现异常现象的常见位置与常见诱因如下:

框架内部抛出的异常:因使用不合规导致
数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时)
业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写 *** 作,导致索引异常等)

表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常)工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)
 

在controller包下建立一个类如下

package com.controller;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ProjectExceptionAdvice {
    @ExceptionHandler(Exception.class)
    public Result doException(Exception e){
        System.out.println("yichang");
        return new Result(null,666);
    }
}

 

 

项目异常分类  自定义项目系统级异常
package com.Exception;

public class SystemException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public SystemException(String message, Integer code) {
        super(message);
        this.code = code;
    }

    public SystemException(String message, Throwable cause, Integer code) {
        super(message, cause);
        this.code = code;
    }


}
自定义项目业务级异常
package com.Exception;

public class BusinessException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public BusinessException(String message, Integer code) {
        super(message);
        this.code = code;
    }

    public BusinessException(String message, Throwable cause, Integer code) {
        super(message, cause);
        this.code = code;
    }

   
}
自定义异常编码
package com.controller;

public class Code {
    public static final Integer SAVE_OK =20011;
    public static final Integer DELETE_OK =20021;
    public static final Integer UPDATE_OK =20031;
    public static final Integer GET_OK =20041;


    public static final Integer SAVE_ERR =20010;
    public static final Integer DELETE_ERR =20020;
    public static final Integer UPDATE_ERR =20030;
    public static final Integer GET_ERR=20040;
}
拦截处理异常

 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/919342.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存