Skip to content

异常处理

通常开发业务系统,有大量需要处理的异常。比如权限不足,数据错误等等。前端通过弹出提示信息的方式告诉用户出了什么错误。 通常情况下我们用 try.....catch.... 对异常进行捕捉处理,但是在实际项目中对业务模块进行异常捕捉,会造成代码重复和繁杂,我们希望代码中只有业务相关的操作,所有的异常我们单独设立一个类来处理它。全局异常就是对框架所有异常进行统一管理。

全局异常处理

系统基于 @RestControllerAdvice 统一定义

java
package com.niu.core.common.config;

import com.niu.core.common.domain.Result;
import com.niu.core.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class NiuExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    @ResponseStatus(code = HttpStatus.METHOD_NOT_ALLOWED)
    public Result handleException(HttpRequestMethodNotSupportedException e) {
        return Result.fail("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("全局异常已处理: Exception-->", e);
        e.printStackTrace();
        if (e instanceof BaseException) {
            BaseException baseException = (BaseException) e;
            return Result.fail(baseException.getCode(), baseException.getMsg());
        }
        return Result.fail(e.getMessage());
    }

    /**
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e) {
        log.error("全局异常已处理: RuntimeException-->", e);
        if (e instanceof BaseException) {
            BaseException baseException = (BaseException) e;
            return Result.fail(baseException.getCode(), baseException.getMsg());
        }
        return Result.fail(e.getMessage());
    }

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("全局异常已处理: MethodArgumentNotValidException-->", e);
        e.printStackTrace();
        log.error(e.getMessage(), e);
        return Result.fail(e.getBindingResult().getFieldError().getDefaultMessage());
    }

}

系统根据不同的业务形式定义了各自的异常返回

具体异常返回在 service 层或者拦截器等即可

基于 MIT 协议发布