如何自定义抛出异常信息

@ExceptionHandler(Exception.class)

package com.lozinn.system.config;

import com.lozinn.system.exception.IException;
import com.lozinn.system.exception.MyException;
import com.lozinn.system.exception.ParameterException;
import com.lozinn.system.exception.TokenException;
import com.lozinn.system.myenum.ExceptionCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionHandler {
    private Logger logger = LoggerFactory.getLogger("MyExceptionHandler");

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map errorHandler(Exception e, HttpServletResponse response){
        Map map = new HashMap<>();
        if(e instanceof IException){
            map.put("code", ((IException) e).getCode());
            map.put("msg", e.getMessage());
        }else if (e instanceof TokenException) {
            map.put("code", ((TokenException) e).getCode());
            map.put("msg", e.getMessage());
        } else if (e instanceof ParameterException){
            map.put("code", ((ParameterException) e).getCode());
            map.put("msg", e.getMessage());
        } else if (e instanceof MaxUploadSizeExceededException){
            map.put("code", ExceptionCodeEnum.MAX_UPLOAD_SIZE_ERROR.getCode());
            map.put("msg", ExceptionCodeEnum.MAX_UPLOAD_SIZE_ERROR.getMsg());
        } else if (e instanceof MyException){
          //自定义的MyException类
            map.put("code", ((MyException) e).getCode());
            map.put("msg", ((MyException) e).getMsg());
        }else {
            // String message = e.getMessage();
            map.put("code", 500);
            // map.put("msg", message == null || message.trim().isEmpty() ? "未知错误" : message);
            map.put("msg", "服务器错误");
        }
        // 日志记录
        logger.error(e.getMessage(), e);
        // 支持跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        return map;
    }
}

自定义MyException extends RuntimeException

其中ExceptionCodeEnum 为自定义的枚举

package com.lozinn.system.exception;

import com.lozinn.system.myenum.ExceptionCodeEnum;
import lombok.Data;

@Data
public class MyException extends RuntimeException {
    private String msg ="服务器异常";
    private int code = 500;

    public MyException(){
        super(ExceptionCodeEnum.UNKNOWN.getMsg());
        this.msg = ExceptionCodeEnum.UNKNOWN.getMsg();
    }

    public MyException(ExceptionCodeEnum eEnum, Throwable e){
        super(eEnum.getMsg(),e);
        this.msg = eEnum.getMsg();
        this.code = eEnum.getCode();
    }

    public MyException(ExceptionCodeEnum eEnum){
        this.msg = eEnum.getMsg();
        this.code = eEnum.getCode();
    }

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

    public MyException(String exception){
        this.msg = exception;
    }
}

抛自定义异常及自定义枚举

if(CollectionUtils.isEmpty(userList)){
            throw new MyException(ExceptionCodeEnum.USER_PWD_ERROR);
}

package com.lozinn.system.myenum;

public enum ExceptionCodeEnum {
    MAX_UPLOAD_SIZE_ERROR(1002, "超过最大允许上传的文件大小"),
    NOT_ENOUGH_MONEY(1003, "余额不足"),
    MALFORMEDJWT_ERROR(1004,"MalformedJwt错误"),
    TOKEN_EXPIRED_ERROR(1005, "token过期,请重新登陆"),
    TOKEN_CHECK_FAIL(1006, "token验证失败,请重新登陆"),
    LOCK_ACCOUND(1007, "账号被锁定"),
    WORKS_IS_VERIFY_ERROR(1008, "当前作品审核中,无法进行修改"),
    PERMISSION_ERROE(1009,"对不起,你没有此操作权限"),
    USER_PWD_ERROR(1010,"账号或密码错误!"),
    USER_EXIST_ERROR(1011,"该用户已经存在"),
    PARAM_ERROR(1012,"参数错误"),

    ERROR_CODE(401,"错误代码401"),
    SUCCESS_CODE(200,"响应成功代码200"),

    UNKNOWN(500,"服务器内部错误,请联系管理员");

    private int code;
    private String msg;
    ExceptionCodeEnum(int code, String msg){
        this.code = code;
        this.msg = 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;
    }

}

结果

图片.png

你可能感兴趣的:(如何自定义抛出异常信息)