Spring boot 全局异常处理

以用@ControllerAdvice进行全局注释

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 未知异常处理
     *
     * @param ex 异常对象
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResponseResult<String> handlerMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        logger.error("Service Error", ex);
        ResponseResult<String> result = new ResponseResult<>();
        result.setReturnCode(BasicException.E_SERVER_ERROR.code());
        result.setReturnData(BasicException.E_PARAM_EXCEPTION.value());
        if (ex.getBindingResult().getErrorCount() > 0) {
            result.setReturnMsg(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        }
        return result;
    }

    /**
     * 未知异常处理
     *
     * @param ex 异常对象
     */
    @ExceptionHandler(value = {BusinessException.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseResult<String> handleBusinessException(BusinessException ex) {
        logger.error("Service Error", ex);
        ResponseResult<String> result = new ResponseResult<>();
        result.setReturnCode(BasicException.E_SERVER_ERROR.code());
        result.setReturnData(BasicException.E_PARAM_EXCEPTION.value());
        result.setReturnMsg(ex.getMessage());
        return result;
    }

    /**
     * 未知异常处理
     *
     * @param ex 异常对象
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseResult<String> handlerException(Exception ex) {
        logger.error("Service Error", ex);
        //TODO 以后整一个类似requestid的东东
        ResponseResult<String> result = new ResponseResult<>();

        result.setReturnCode(BasicException.E_SERVER_ERROR.code());
        result.setReturnMsg(BasicException.E_SERVER_ERROR.value());
        result.setReturnData(BasicException.E_SERVER_ERROR.value());
        return result;
    }

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


}
上一篇
下一篇