java自定义异常处理和抛出异常

标签:java异常处理、自定义异常处理、抛出自定义异常

异常处理是我们开发中常见的的问题,当程序出现异常,我们是不能让异常直接打印到页面的,需要进行处理并返回一个错误提示

如下图

我们先自定义一个异常类,字段有异常代码和异常描述

@Data
@EqualsAndHashCode(callSuper = true)
public class ReturnException extends Exception {

    /** 异常信息 */
    private String responseMessage = "接口错误";

    /** 异常码*/
    private String responseCode = "0";

    /**
     * 有参构造
     */
    public ReturnException(String responseCode,String responseMessage ) {
        this.responseCode = responseCode;
        this.responseMessage = responseMessage;
    }

    /**
     * 无参构造
     */
    public ReturnException() {
    }
}

添加 ExceptionHandler 异常处理 

启动类需要加上

@ComponentScan(basePackages = {"com.xxx"})
@ServletComponentScan(basePackages = "com.xxx")
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {
    // ExceptionHandler  将自定义异常类(ReturnException)加进去
    @ExceptionHandler({Exception.class, RuntimeException.class, ReturnException.class})
    @ResponseBody
    public Object dealtExceptionsHandler(HttpServletRequest request, Exception e) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 判断是否是自定义异常类抛出异常
        if (e instanceof ReturnException) {
            map.put("ret", ((ReturnException) e).getResponseCode());
            map.put("msg", ((ReturnException) e).getResponseMessage());
            return map;
        } else {
            map.put("ret", 0);
            map.put("msg", "接口错误");
            return map;
        }
    }
}

这样一个简单的异常处理就可以了, 下面我们根据一个小案例做个实验吧

这是一个简单的参数验证(Chaining是一个我自己写的一个链式表单验证,代码在下面) 

@GetMapping("/formValidator")
@ResponseBody
public Map<String, Object> formValidator(
        @ApiParam(value = "用户名",required = false) @RequestParam(value = "userName",required = false)String userName,
        @ApiParam(value = "手机号",required = false) @RequestParam(value = "phone",required = false)String phone,
        @ApiParam(value = "部门",required = false) @RequestParam(value = "deptname",required = false)String deptname,
        HttpServletRequest req, HttpServletResponse resp) throws ReturnException {

    Map<String, Object> map = new HashMap<String, Object>();

    Chaining chaining = new Chaining();
    chaining
            .paramName("用户名")
            .stringIsEmpty(userName)
            .stringMin(userName, 2)
            .stringMax(userName, 10)
            .paramName("手机号")
            .stringIsEmpty(phone)
            .phoneValidator(phone);

    map.put("ret", "1");
    map.put("msg","访问成功");
    return map;
}

我么用postman进行测试

Chaining链式表单验证  详细信息请点传送门:https://blog.csdn.net/qq_39997045/article/details/111996434 

/**
 * @author qi
 * @date 2020/12/30
 */
public class Chaining {

    /**
     * 邮箱
     */
    private String mail;

    /**
     * 手机号
     */
    private String phone;

    /**
     * 参数名称
     */
    private String paramName;

    /**
     * 参数
     */
    private String param;

    public Chaining() {

    }

    /**
     * 设置参数名称, 用来拼接提示
     */
    public Chaining paramName(String parName) {
        this.paramName = parName;
        return this;
    }

    /**
     * 判断参数不能为空
     */
    public Chaining stringIsEmpty(String mail) throws ReturnException {

        if (mail==null) {
            throw new ReturnException("3", paramName + "不能为NULL");
        }

        if ("null".equalsIgnoreCase(mail)){
            throw new ReturnException("3", paramName + "不能为NULL");
        }

        if (mail.trim().isEmpty()){
            throw new ReturnException("3", paramName + "不能为空字符");
        }

        this.mail = mail;
        return this;
    }

    /**
     * 邮箱格式验证
     */
    public Chaining mailValidator(String mail) throws ReturnException {
        if (!Pattern.matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", mail)) {
            throw new ReturnException("3", paramName + "格式错误");
        }
        this.mail = mail;
        return this;
    }

    /**
     * 手机格式验证
     */
    public Chaining phoneValidator(String phone) throws ReturnException {
        if (!Pattern.matches("^((13[0-9])|(15[^4,\\D])|(16[6])|(17[0-9])|(18[0-9])||(19[8-9]))\\d{8}$", phone)) {
            throw new ReturnException("3", paramName + "格式错误");
        }
        this.phone = phone;
        return this;
    }

    /**
     * 字符最大限制
     */
    public Chaining stringMax(String param, Integer max) throws ReturnException {
        if (param.length()>max) {
            throw new ReturnException("3", paramName +"超过字段最大限制(" + max+ ")");
        }
        return this;
    }

    /**
     * 字符最小限制
     */
    public Chaining stringMin(String param, Integer min) throws ReturnException {
        if (param.length()<min) {
            throw new ReturnException("3", "低于字段最小限制(" +min+ ")");
        }
        return this;
    }
}

今天是元旦祝大家节日快乐

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值