java 异常处理,自定义异常

作者: adm 分类: java 发布时间: 2023-11-08

全局异常类

/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalException {

    /**
     * 处理所有不可知异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<Object> handleException(Exception e) {
        if (GlobalConfig.debug) {
            e.printStackTrace();
        }
        log.error("系统异常 {}", e.getMessage());
        return Result.failed(ErrorEnum.SYSTEM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 拦截404异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public Result<Object> handleNoHandlerFoundException(NoHandlerFoundException e){
        return Result.failed(ErrorEnum.REQUEST_404_ERROR.getCode(), e.getMessage());
    }

    /**
     * 拦截自定义抛出异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public Result<Object> handleException(MyCustomException e) {
        int code = e.getCode();
        String msg = e.getMsg();
        return Result.failed(code, msg);
    }

    /**
     * 拦截表单参数校验FROM
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result<Object> handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        Integer code = ErrorEnum.PARAMS_VALID_ERROR.getCode();
        String msg   = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
        return Result.failed(code, msg);
    }

    /**
     * 拦截路径参数校验PATH
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public Result<Object> handlePathException(MissingServletRequestParameterException e) {
        Integer code = ErrorEnum.PARAMS_VALID_ERROR.getCode();
        String msg   = Objects.requireNonNull(e.getMessage());
        return Result.failed(code, msg);
    }

    /**
     * 拦截JSON参数校验
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Integer code = ErrorEnum.PARAMS_VALID_ERROR.getCode();
        String msg   = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
        return Result.failed(code, msg);
    }

    /**
     * 拦截参数类型不正确
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result<Object> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        Integer code = ErrorEnum.PARAMS_TYPE_ERROR.getCode();
        String msg   = Objects.requireNonNull(e.getMessage());
        return Result.failed(code, msg.split(";")[0]);
    }

    /**
     * 拦截请求方法
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Result<Object> handleRequestMethodException(HttpRequestMethodNotSupportedException e) {
        Integer code = ErrorEnum.REQUEST_METHOD_ERROR.getCode();
        String msg   = Objects.requireNonNull(e.getMessage());
        return Result.failed(code, msg);
    }

    /**
     * 拦截断言异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public Result<Object> handleIllegalArgumentException(IllegalArgumentException e) {
        Integer code = ErrorEnum.ASSERT_ARGUMENT_ERROR.getCode();
        String msg   = Objects.requireNonNull(e.getMessage());
        return Result.failed(code, msg);
    }

    /**
     * 拦截MybatisPlus异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MybatisPlusException.class)
    @ResponseBody
    public Result<Object> handleMybatisPlusException(MybatisPlusException e) {
        Integer code = ErrorEnum.ASSERT_MYBATIS_ERROR.getCode();
        String msg   = Objects.requireNonNull(e.getMessage());
        return Result.failed(code, msg);
    }

}

自定义异常

@Data
public class MyCustomException  extends RuntimeException{

    private Integer code;
    private String msg;

    public MyCustomException(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

}

ErrorEnum

public enum ErrorEnum {

    SUCCESS(200, "成功"),
    FAILED(300, "失败"),
    PARAMS_VALID_ERROR(310, "参数校验错误"),
    PARAMS_TYPE_ERROR(311, "参数类型错误"),
    REQUEST_METHOD_ERROR(312, "请求方法错误"),
    ASSERT_ARGUMENT_ERROR(313, "断言参数错误"),
    ASSERT_MYBATIS_ERROR(314, "断言Mybatis错误"),

    LOGIN_ACCOUNT_ERROR(330, "登录账号或密码错误"),
    LOGIN_DISABLE_ERROR(331, "登录账号已被禁用了"),
    TOKEN_EMPTY(332, "token参数为空"),
    TOKEN_INVALID(333, "token参数无效"),
    CAPTCHA_ERROR(334, "验证码错误"),
    PAYMENT_ERROR(335, "发起支付失败"),

    NO_PERMISSION(403, "无相关权限"),
    REQUEST_404_ERROR(404, "请求接口不存在"),

    SYSTEM_ERROR(500, "系统错误");

    /**
     * 构造方法
     */
    private final int code;
    private final String msg;
    ErrorEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    /**
     * 获取状态码
     *
     * @author fzr
     * @return Long
     */
    public int getCode() {
        return this.code;
    }

    /**
     * 获取提示
     *
     * @author fzr
     * @return String
     */
    public String getMsg() {
        return this.msg;
    }

}

Result

@Data
public class Result<T> {

    /** 状态码 **/
    private Integer code;

    /** 提示信息 **/
    private String msg;

    /** 响应数据 **/
    private T data;

    /** 无参构造 **/
    protected Result() {}

    /**
     * 带参构造
     *
     * @author fzr
     * @param code 状态码
     * @param msg 提示信息
     * @param data 响应数据
     */
    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 成功返回结果
     *
     * @author fzr
     * @return Result
     */
    public static Result<Object> success() {
        return new Result<>(ErrorEnum.SUCCESS.getCode(), ErrorEnum.SUCCESS.getMsg(), new ArrayList<>());
    }

    /**
     * 成功返回结果
     *
     * @author fzr
     * @param code 状态码
     * @return Result
     */
    public static Result<Object> success(Integer code) {
        return new Result<>(code, ErrorEnum.SUCCESS.getMsg(), new ArrayList<>());
    }

    /**
     * 成功返回结果
     *
     * @author fzr
     * @param msg 提示信息
     * @return Result
     */
    public static Result<Object> success(String msg) {
        return new Result<>(ErrorEnum.SUCCESS.getCode(), msg, new ArrayList<>());
    }

    /**
     * 成功返回结果
     *
     * @author fzr
     * @param data 响应数据
     * @return Result
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(ErrorEnum.SUCCESS.getCode(), ErrorEnum.SUCCESS.getMsg(), data);
    }

    /**
     * 成功返回结果
     *
     * @author fzr
     * @param code 状态码
     * @param msg 提示信息
     * @return Result
     */
    public static Result<Object> success(Integer code, String msg) {
        return new Result<>(code, msg, new ArrayList<>());
    }

    /**
     * 成功返回结果
     *
     * @author fzr
     * @param msg 提示信息
     * @param data 响应数据
     * @return Result
     */
    public static <T> Result<T> success(String msg, T data) {
        return new Result<>(ErrorEnum.SUCCESS.getCode(), msg, data);
    }

    /**
     * 成功返回结果
     *
     * @author fzr
     * @param code 状态码
     * @param msg 提示信息
     * @param data 响应数据
     * @return Result
     */
    public static <T> Result<T> success(Integer code, String msg, T data) {
        return new Result<>(code, msg, data);
    }

    /**
     * 响应失败结果
     *
     * @author fzr
     * @param code 状态码
     * @return Result
     */
    public static Result<Object> failed(Integer code) {
        return new Result<>(code, ErrorEnum.FAILED.getMsg(), new ArrayList<>());
    }

    /**
     * 响应失败结果
     *
     * @author fzr
     * @param msg 提示信息
     * @return Result
     */
    public static Result<Object> failed(String msg) {
        return new Result<>(ErrorEnum.FAILED.getCode(), msg, new ArrayList<>());
    }

    /**
     * 响应失败结果
     *
     * @author fzr
     * @param data 响应数据
     * @return Result
     */
    public static <T> Result<T> failed(T data) {
        return new Result<T>(ErrorEnum.FAILED.getCode(), ErrorEnum.FAILED.getMsg(), data);
    }

    /**
     * 响应失败结果
     *
     * @author fzr
     * @param code 状态码
     * @param msg 提示信息
     * @return Result
     */
    public static Result<Object> failed(Integer code, String msg) {
        return new Result<>(code, msg, new ArrayList<>());
    }

    /**
     * 响应失败结果
     *
     * @author fzr
     * @param code 状态码
     * @param msg 提示信息
     * @param data 响应数据
     * @return Result
     */
    public static <T> Result<T> failed(Integer code, String msg, T data) {
        return new Result<>(code, msg, data);
    }

}

实例参数验证

package cn.wmadmin.co2.validate;

import io.swagger.annotations.ApiModel;
import lombok.Data;

import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import java.io.Serializable;

@Data
@ApiModel("分页参数")
public class PageValidate implements Serializable {

    private static final long serialVersionUID = 1L;

    // 当前分页
    @DecimalMin(value = "1", message = "page参数必须大于0的数字")
    public Integer page = 1;

    // 每页条数
    @DecimalMin(value = "1", message = "pageSize参数必须是大于0的数字")
    @DecimalMax(value = "60", message = "pageSize参数必须是小于60的数字")
    private Integer limit = 20;

}

@GetMapping("list")
    public Result<?> listByPage(Co2Products dto, @Validated PageValidate pageValidate){
        LambdaQueryWrapper<Co2Products> wrapper=new LambdaQueryWrapper<>();
        if(dto.getProductName()!=null){
            wrapper.eq(Co2Products::getProductName,dto.getProductName());
        }
        IPage<Co2Products> result = co2ProductsService.listByPage(pageValidate,wrapper);
        return Result.OK(result);
    }

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!