SpringBoot之统一异常处理

异常,不仅仅是程序运行状态的描述,还可以使得代码编写更加的规范
 
1、自定义异常:FieldValueInvalidException
package com.geniuses.sewage_zero_straight.exception;

import com.geniuses.sewage_zero_straight.enums.CodeAndMsgEnum;

/**
 * 字段取值无效异常
 */
public class FieldValueInvalidException extends RuntimeException {

    //CodeAndMsgEnum 定义了一个枚举类
    public FieldValueInvalidException(CodeAndMsgEnum codeAndMsgEnum){
        super(codeAndMsgEnum.getMsg());
        this.code = codeAndMsgEnum.getCode();
        this.msg = codeAndMsgEnum.getMsg();
    }

    public FieldValueInvalidException(int code, String msg){
        this.code = code;
        this.msg = msg;
    }

    private int code;
    private String msg;

    public int getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

2、定义异常处理器

package com.geniuses.sewage_zero_straight.advice;

import com.geniuses.sewage_zero_straight.bean.view.ResultView;
import com.geniuses.sewage_zero_straight.exception.FieldValueInvalidException;
import com.geniuses.sewage_zero_straight.exception.ParamNotExistException;
import com.geniuses.sewage_zero_straight.exception.ResourceNotExistException;
import com.geniuses.sewage_zero_straight.util.ResultViewUtil;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * controller错误处理增强器
 */
@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {

    /**
     * 全局ParamNotExistException异常处理器
     * @param paramNotExistException
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ParamNotExistException.class)
    public ResultView paramNotExistExceptionHandler(ParamNotExistException paramNotExistException){
        return ResultViewUtil.init(paramNotExistException.getCode(), paramNotExistException.getMsg(), null);
    }


    /**
     * 全局ResourceNotExistException异常处理器
     * @param resourceNotExistException
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ResourceNotExistException.class)
    public ResultView resourceNotExistException(ResourceNotExistException resourceNotExistException){
        return ResultViewUtil.init(resourceNotExistException.getCode(), resourceNotExistException.getMsg(), null);
    }

    /**
     * 全局FieldValueInvalidException异常处理器
     * @param fieldValueInvalidException
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = FieldValueInvalidException.class)
    public ResultView fieldValueInvalidException(FieldValueInvalidException fieldValueInvalidException){
        return ResultViewUtil.init(fieldValueInvalidException.getCode(), fieldValueInvalidException.getMsg(), null);
    }
}

 

posted @ 2019-03-18 16:14  拂衣志  阅读(255)  评论(0编辑  收藏  举报