https://blog.csdn.net/qq_38234785/article/details/118853915

二、代码
CodeMsg.java

package com.example.bloomfilter.bean;

/**
 * @Author: dyl
 * @Data: 2021/7/17
 * @Description: 异常返回信息
 *
 */

public class CodeMsg {
    private int code;
    private String msg;

    //通用异常
    public static CodeMsg SUCCESS = new CodeMsg(0, "success");
    public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服务端异常");
    //注意  %s ,格式化字符串
    public static CodeMsg SERVER_BIND_ERROR = new CodeMsg(500101, "服务端绑定异常:%s");
    //登录模块 5002XX
    public static CodeMsg MSG_NAME_IS_EMPTY = new CodeMsg(500200, "用户名不能为空!");
    public static CodeMsg MSG_PASSWORD_IS_EMPTY = new CodeMsg(500201, "密码不能为空!");
    public static CodeMsg MSG_MOBILE_ERROR = new CodeMsg(500202, "手机号格式不正确!");
    public static CodeMsg MSG_MOBILE_IS_EMPTY = new CodeMsg(500203, "手机号不能为空!");
    public static CodeMsg    MSG_MOBILE_NOT_EXIST = new CodeMsg(500204, "手机号不存在!");
    public static CodeMsg    MSG_PASSWORD_ERROR = new CodeMsg(500205, "密码错误!");


    private CodeMsg(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    public CodeMsg fillArgs(Object ... args){
        int code=this.code;
        String message=String.format(msg,args);
        return new CodeMsg(code,message);
    }
    public int getCode() {
        return code;
    }
    public String getMsg() {
        return msg;
    }
}

GlobalException.java

package com.example.bloomfilter.bean;

/**
 * @Author: dyl
 * @Data: 2021/7/17
 * @Description: 全局异常类
 *
 */
public class GlobalException extends RuntimeException{
    private CodeMsg codeMsg;
    public GlobalException(CodeMsg codeMsg){
        super(codeMsg.toString());
        this.codeMsg=codeMsg;
    }

    public CodeMsg getCodeMsg() {
        return codeMsg;
    }
}

GlobalExceptionHandler.java


package com.example.bloomfilter.handler;

import com.example.bloomfilter.bean.CodeMsg;
import com.example.bloomfilter.bean.GlobalException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: dyl
 * @Data: 2021/7/17
 * @Description: 异常拦截器
 *
 */

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public CodeMsg exceptionHandler(HttpServletRequest request, Exception e) {
        // 本地自定义异常处理
        if(e instanceof GlobalException){
            return ((GlobalException) e).getCodeMsg();
        }
        //绑定异常是需要明确提示给用户的
        else if (e instanceof BindException) {
            BindException exception = (BindException) e;
            List<ObjectError> errors = exception.getAllErrors();
            String msg = errors.get(0).getDefaultMessage();//获取自错误信息
            return CodeMsg.SERVER_BIND_ERROR.fillArgs(msg);//将具体
            //错误信息设置到CodeMsg中返回
        }
        // 系统异常处理
        return CodeMsg.SERVER_BIND_ERROR.fillArgs(e.getCause() + e.getMessage());//将具体
    }
}


HelloController.java


package com.example.bloomfilter.controller;

//import com.example.bloomfilter.apibean.ApiService;
import com.example.bloomfilter.bean.CodeMsg;
import com.example.bloomfilter.bean.GlobalException;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/exceptionTest")
    @ResponseBody
    public String  exceptionTest() {
        int num = 1 / 0;
        return "ExTest";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String  login(@RequestParam(name = "name") String name,
                         @RequestParam(name = "pass") String pass) {
        // 账户空异常
        if(name == "" || name == null)
            throw new GlobalException(CodeMsg.MSG_NAME_IS_EMPTY);
        // 密码空异常
        if(pass == "" || pass == null)
            throw new GlobalException(CodeMsg.MSG_PASSWORD_IS_EMPTY);
        // 密码错误异常
        if(pass != "123456" && !pass.equals("123456"))
            throw new GlobalException(CodeMsg.MSG_PASSWORD_ERROR);
        // 登陆成功
        return "login success!";
    }
}

三、测试
http://localhost:8080/exceptionTest

{

“code”: 500101,

“msg”: “服务端绑定异常:null/ by zero”

}
文档更新时间: 2024-05-20 13:24   作者:admin