springboot定义全局异常处理类GlobalExceptionHandler

定义全局异常处理类

注意:如果需要返回页面,则要删掉@ResponseBody注解

package com.xiyan.mydemo.common.config;

import com.xiyan.mydemo.common.utils.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author xiyan
 * @Date 2020/6/11
 * @Version 1.0
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获未知异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler
    public ApiResult unknowException(Exception e){
        log.info("未知异常:"+e.getMessage());
        e.printStackTrace();//后台输出具体异常
        return ApiResult.unknowError();
    }

    /**
     * 捕获运行时异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ApiResult runtimeExceptionHandler(final RuntimeException e) {
        log.info("运行时异常:"+e.getMessage());
        e.printStackTrace();//后台输出具体异常
        return ApiResult.runtimeError(e.getMessage());
    }

    /**
     * 捕获自定义异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public ApiResult customExceptionHandler(final CustomException e) {
        log.info("自定义异常:"+e.getMessage());
        e.printStackTrace();//后台输出具体异常
        return ApiResult.error(e.getMessage());
    }

}

以下为扩展部分

日志打印@Slf4j和@Data用到了lombok

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

返回参数封装

注:可自定义

package com.xiyan.mydemo.common.utils;

import lombok.Data;

/**
 * 封装返回参数工具类
 * @Author xiyan
 * @Date 2020/6/11
 * @Version 1.0
 */
@Data
public class ApiResult {
    private Boolean flag;
    private Integer code;
    private String msg;
    private Object data;

    public ApiResult(Boolean flag, Integer code, String msg, Object data) {
        super();
        this.flag = flag;
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ApiResult(Boolean flag, Integer code, String msg) {
        super();
        this.flag = flag;
        this.code = code;
        this.msg = msg;
    }

    public static ApiResult success() {
        return new ApiResult(Boolean.TRUE,200,"操作成功");
    }

    public static ApiResult success(Object data) {
        return new ApiResult(Boolean.TRUE,200,"操作成功",data);
    }

    /**
     * 操作失败
     * @param msg 失败原因
     * @return
     */
    public static ApiResult error(String msg) {
        return new ApiResult(Boolean.FALSE,201,msg);
    }

    public static ApiResult unknowError() {
        return new ApiResult(Boolean.FALSE,500,"系统发生未知异常,请联系管理员");
    }
    public static ApiResult runtimeError(String msg) {
        return new ApiResult(Boolean.FALSE,400,msg);
    }
}

引用示例

@Override
    public int insertEntity(UserInfoVO vo) {
        if (StringUtils.isBlank(vo.getUsername()) || StringUtils.isBlank(vo.getPassword())) {
            throw new RuntimeException("用户名或密码不能为空");
        }
        if(!RegexUtils.checkUsername(vo.getUsername())){
            throw new CustomException(RegexUtils.REGEX_USERNAME_ERROR);
        }
        if(!RegexUtils.checkPasswprd(vo.getPassword())){
            throw new RuntimeException(RegexUtils.REGEX_PASSWORD_ERROR);
        }
        if(userInfoMapper.selectOneByUserName(vo.getUsername())){
            throw new RuntimeException("用户名("+vo.getUsername()+")已被注册");
        }
        String salt = randomSalt();
        UserInfo entity = UserInfo.builder().userId(GenarateIdUtils.getUserId()).username(vo.getUsername())
                .salt(salt).password(encryptPassword(vo.getUsername(), vo.getPassword(), salt)).build();
        return userInfoMapper.insertEntity(entity);
    }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值