Springboot项目异常处理

在项目中出现的异常是五花八门的,假如你要发送一个参数为1的数字,用户给了一个heihei的字符串,这是不规范的用户行为导致的。那么怎么处理这些异常呢?

还有可能数据库服务器因为断电挂了,某个倒霉蛋把电源踢掉了都是有可能出现异常的。

创建业务异常类

package com.hxut.exception;

/**
 * description: BusinessException
 * date: 2022/5/26 21:41
 * author: MR.孙
 */
public class BusinessException extends RuntimeException{
    private Integer code;


    public Integer getCode() {
        return code;
    }

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

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

创建系统异常类

package com.hxut.exception;

/**
 * description: SystemException
 * date: 2022/5/26 21:38
 * author: MR.孙
 */
public class SystemException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

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

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

将可能出现的异常进行,包装(try-catch)

  @Override
    public Result<Boolean> delete(Integer id) {
        if(id==37){
            throw new BusinessException(Response.Code.BAD_REQUEST.code(),Response.Code.BAD_REQUEST.msg());
        }
        try {
            //将可能出现的异常进行包装,转换成自定义异常
            int i=1/0;
        }catch (Exception e){
            throw new SystemException(Response.Code.UNKNOWN.code(), e.getMessage(),e);
        }

        Boolean data = bookMapper.deleteById(id) > 0;
        return Result.ok(Response.Code.DELETE_SUCCESS.code(),Response.Code.DELETE_SUCCESS.msg(),data);
    }

发生的异常统统交给异常处理器

package com.hxut.exception;


import com.hxut.domain.Response;
import com.hxut.domain.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//作为springMVC的异常处理器
//@ControllerAdvice
@RestControllerAdvice
public class ProjectExceptionAdvice {

    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException e){
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,e对象发送给开发人员
        e.printStackTrace();
        return Result.failed(e.getCode(),e.getMessage(),null);
    }

    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException e){
        e.printStackTrace();
        return Result.failed(e.getCode(),e.getMessage(),null);
    }


    //拦截所有的异常信息
    @ExceptionHandler(Exception.class)
    public Result doException(Exception e){
        e.printStackTrace();

        System.out.println("嘿嘿,异常你往哪里跑!");
        return Result.failed(Response.Code.UNKNOWN.code(),Response.Code.UNKNOWN.msg(),null);
    }

}

posted @ 2022-05-26 22:05  长情c  阅读(134)  评论(0)    收藏  举报