自定义异常和controller异常集中处理

1.自定义异常

/**
 * 自定义异常
 */
public class MyException extends RuntimeException {
    public MyException(String message){
        super(message);
    }
}

1.1自定义异常使用

 //参数判断
        if ("".equals(tenantDto.getUsername()) || tenantDto.getUsername()==null){
           throw new MyException(ErrorCode.ERROR_CODE_USERNAME_NULL.getErrorMsg());
        }else {
            Employee employee = employeeMapper.findEmployeeByUsername(tenantDto.getUsername());
            if (employee != null){
                throw new MyException(ErrorCode.ERROR_CODE_USERNAME_REPEAT.getErrorMsg());
            }
        }

1.2定义异常常量

package com.wal.hrm.contants;

public enum ErrorCode {
	//异常信息常量对象
    ERROR_CODE_USERNAME_NULL(1000,"公司账号不能为空"),
    ERROR_CODE_USERNAME_REPEAT(2000,"该账号已被注册");

    private int errorcode;
    private String errorMsg;
    ErrorCode(int errorCode, String errorMsg) {
        this.errorcode = errorCode;
        this.errorMsg=errorMsg;
    }

    public int getErrorcode() {
        return errorcode;
    }

    public void setErrorcode(int errorcode) {
        this.errorcode = errorcode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}

2.controller中的异常集中处理

/**
 * controller异常集中处理
 * @ControllerAdvice 对controller的增强
 * @ExceptionHandler 标记该方法是对controller异常的处理方法
 * MyException.class,指定具体异常
 */

@ControllerAdvice
@ResponseBody
public class CommonExceptionHandler {

    //处理自定义异常的方法MyException
    @ExceptionHandler(MyException.class)
    public AjaxResult myException(MyException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("保存对象失败!"+e.getMessage());
    }

    //处理exception异常
    @ExceptionHandler(Exception.class)
    public AjaxResult exception(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("后台程序出错,正在杀程序员。。。");
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值