欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springmvc全局异常处理

程序员文章站 2022-04-21 23:48:35
...

目录

1.提供项目业务异常枚举接口

2.封装项目业务异常枚举

3.封装项目业务异常

4.定义全局异常拦截器

5.抛出异常

-------------------------2018-9-13更新---------------------------------

加入了Google翻译,翻译异常名为中文。


1.提供项目业务异常枚举接口

,用于获取异常code和异常message



/**
 * <p>
 * 说明:业务异常抽象接口
 * </p>
 *
 * @author lgl
 */
public interface ServiceExceptionEnum {

    /**
     * <p>
     * 说明:获取异常编码
     * </p>
     */
    int getCode();

    /**
     * <p>
     * 说明:获取异常信息
     * </p>
     */
    String getMessage();
}

2.封装项目业务异常枚举

,实现业务异常接口



/**
 * <p>
 * 说明:业务异常枚举
 * </p>
 *
 * @author lgl
 */
public enum BizExceptionEnum implements ServiceExceptionEnum {

    //只写几个展示
    OK(1, "操作成功"),
    NOT_LOGIN(-1, "用户未登陆"),
    CAN_NOT_NULL(-2, "不能为空"),
    PARAMER_TYPE_ERROR(-3, "参数类型错误");

    BizExceptionEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    private int code;

    private String message;

    @Override
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

3.封装项目业务异常

,从异常枚举接口里获取异常数据,这里是pobc项目


/**
 * <p>
 * 说明:封装pobc业务异常
 * </p>
 *
 * @author lgl
 */
public class PobcException extends RuntimeException {

    /**
     * <p>
     * 说明:返回码
     * </p>
     */
    private int code;

    /**
     * <p>
     * 说明:返回消息
     * </p>
     */
    private String message;

    public PobcException() {
    }

    public PobcException(ServiceExceptionEnum serviceExceptionEnum) {
        this.code = serviceExceptionEnum.getCode();
        this.message = serviceExceptionEnum.getMessage();
    }

    public PobcException(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

4.定义全局异常拦截器

,要被扫描器扫到哦!


import com.fushoukeji.pobc.common.model.Result;
import com.fushoukeji.pobc.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLException;


/**
 * <p>
 * 说明:全局的的异常拦截器(拦截所有的控制器)(带有@xxxMapping注解的方法上都会拦截)
 * 以下只写了几种异常拦截,用于展示
 * </p>
 *
 * @author lgl
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * <p>
     * 说明:拦截业务异常
     * </p>
     */
    @ExceptionHandler(PobcException.class)
    @ResponseBody
    public Result<Object> serviceException(PobcException e) {
        log.error("业务异常:", e);
        return new ResultUtil<Object>().setErrorMsg(e.getCode(), e.getMessage());
    }

    /**
     * 参数不合法异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result<Object> handleValidationException(ConstraintViolationException e) {
        for (ConstraintViolation<?> s : e.getConstraintViolations()) {
            return new ResultUtil<Object>().setErrorMsg(s.getInvalidValue() + ": " + s.getMessage());
        }
        return new ResultUtil<Object>().setErrorMsg("请求参数不合法");
    }

    /**
     * <p>
     * 说明:拦截未知的运行异常
     * </p>
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result<Object> unKnownException(RuntimeException e) {
        log.error("运行时异常:", e);
        return new ResultUtil<Object>().setErrorMsg(BizExceptionEnum.UNKNOW_ERROR.getCode(), BizExceptionEnum.UNKNOW_ERROR.getMessage());
    }

    @ExceptionHandler(SQLException.class)
    @ResponseBody
    public Result<Object> db2ConnectException(SQLException e) {
        log.error("数据库异常:", e);
        return new ResultUtil<Object>().setErrorMsg(BizExceptionEnum.NETWORK_TIMEOUT.getCode(), BizExceptionEnum.NETWORK_TIMEOUT.getMessage());
    }

}

5.抛出异常

service层抛出异常就行了,controller层用不着try catch了,controller层只需要有@XxxMapping就行了

    @Override
    public int stopUser(Long id) {
        TUser tbUser = tUserMapper.selectByPrimaryKey(id);
        tbUser.setState(PobcEnum.STOP_USING.getValue());
        tbUser.setUpdateTime(DateTime.now().toString());
        if (tUserMapper.updateByPrimaryKeySelective(tbUser) != 1) {
            //抛出异常
            throw new PobcException(BizExceptionEnum.USER_STOP_FAIL);
        }
        return 1;
    }

    @Override
    public int startUser(Long id) {
        TUser tbUser = tUserMapper.selectByPrimaryKey(id);
        tbUser.setState(PobcEnum.START_USING.getValue());
        tbUser.setUpdateTime(DateTime.now().toString());
        if (tUserMapper.updateByPrimaryKeySelective(tbUser) != 1) {
            throw new PobcException(BizExceptionEnum.USER_START_FAIL);
        }
        return 1;
    }

-------------------------2018-9-13更新---------------------------------

加入了Google翻译,翻译异常名为中文。

代码:https://download.csdn.net/download/qq_24615069/10665129

忘了上传js。。。。。这里贴上代码,放在resources下的tk文件夹里,名称为Google.js

function token(a) {
    var k = "";
    var b = 406644;
    var b1 = 3293161072;

    var jd = ".";
    var sb = "+-a^+6";
    var Zb = "+-3^+b+-f";

    for (var e = [], f = 0, g = 0; g < a.length; g++) {
        var m = a.charCodeAt(g);
        128 > m ? e[f++] = m: (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023), e[f++] = m >> 18 | 240, e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224, e[f++] = m >> 6 & 63 | 128), e[f++] = m & 63 | 128)
    }
    a = b;
    for (f = 0; f < e.length; f++) a += e[f],
    a = RL(a, sb);
    a = RL(a, Zb);
    a ^= b1 || 0;
    0 > a && (a = (a & 2147483647) + 2147483648);
    a %= 1E6;
    return a.toString() + jd + (a ^ b)
};

function RL(a, b) {
    var t = "a";
    var Yb = "+";
    for (var c = 0; c < b.length - 2; c += 3) {
        var d = b.charAt(c + 2),
        d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
        d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
        a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
    }
    return a
}

controller示例

@Api(description = "指标控制器")
@RestController
@RequestMapping(value = "/indicator")
public class IndicatorController {

    @Autowired
    private IndicatorService indicatorService;

    @ApiOperation(value = "新增指标大类")
    @PostMapping(value = "/category/create")
    public Result<Object> createICategory(@RequestBody IndicatorCategory indicatorCategory) {
        indicatorService.createIndicatorCategory(indicatorCategory);
        return new ResultUtil<>().setData(null, "新增成功");
    }
}

service示例:只管抛

@Service
public class IndicatorServiceImpl implements IndicatorService {

    private static final Logger log = LoggerFactory.getLogger(IndicatorServiceImpl.class);

    @Autowired
    private IndicatorCategoryMapper indicatorCategoryMapper;

    @Override
    public void createIndicatorCategory(IndicatorCategory indicatorCategory) {
        try {
            indicatorCategoryMapper.insertSelective(indicatorCategory);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new GlobalException(500, e);
        }
    }

 

相关标签: 全局异常处理