首页

通过Spring的@ExceptionHandler拦截处理自定义异常并标准化结果返回

标签:ExceptionHandler,异常拦截,RestControllerAdvice     发布时间:2022-10-18   

一、定义全局接口异常处理的类

基于spring的org.springframework.web.bind.annotation.RestControllerAdvice 是全局接口异常处理GlobalExceptionHandlerAdvice类,当发生异常没有捕获时,@ExceptionHandler便标记自定义处理入口方法

 import com.louis.springboot.demo.entity.Result;@b@ import lombok.extern.slf4j.Slf4j;@b@import org.springframework.web.bind.annotation.ExceptionHandler;@b@import org.springframework.web.bind.annotation.RestControllerAdvice;@b@@b@@RestControllerAdvice@b@@Slf4j@b@public class GlobalExceptionHandlerAdvice extends DefaultGlobalExceptionHandlerAdvice {@b@@b@    @ExceptionHandler(value = {UserNotFoundException.class})@b@    public Result userNotFound(UserNotFoundException ex) {@b@        log.error(ex.getMessage());@b@        return Result.fail(ex.getErrorType());@b@    }@b@}

二、DefaultGlobalExceptionHandlerAdvice类 -用于处理通用基础异常

import com.louis.springboot.demo.entity.Result;@b@import lombok.extern.slf4j.Slf4j;@b@import org.springframework.dao.DuplicateKeyException;@b@import org.springframework.http.HttpStatus;@b@import org.springframework.web.bind.MethodArgumentNotValidException;@b@import org.springframework.web.bind.MissingServletRequestParameterException;@b@import org.springframework.web.bind.annotation.ExceptionHandler;@b@import org.springframework.web.bind.annotation.ResponseStatus;@b@import org.springframework.web.multipart.MultipartException;@b@ @b@@Slf4j@b@public class DefaultGlobalExceptionHandlerAdvice {@b@@b@    @ExceptionHandler(value = {MissingServletRequestParameterException.class})@b@    public Result missingServletRequestParameterException(MissingServletRequestParameterException ex) {@b@        log.error("missing servlet request parameter exception:{}", ex.getMessage());@b@        return Result.fail(SystemErrorType.ARGUMENT_NOT_VALID);@b@    }@b@@b@    @ExceptionHandler(value = {MultipartException.class})@b@    public Result uploadFileLimitException(MultipartException ex) {@b@        log.error("upload file size limit:{}", ex.getMessage());@b@        return Result.fail(SystemErrorType.UPLOAD_FILE_SIZE_LIMIT);@b@    }@b@@b@    @ExceptionHandler(value = {MethodArgumentNotValidException.class})@b@    public Result serviceException(MethodArgumentNotValidException ex) {@b@        log.error("service exception:{}", ex.getMessage());@b@        return Result.fail(SystemErrorType.ARGUMENT_NOT_VALID, ex.getBindingResult().getFieldError().getDefaultMessage());@b@    }@b@@b@    @ExceptionHandler(value = {DuplicateKeyException.class})@b@    public Result duplicateKeyException(DuplicateKeyException ex) {@b@        log.error("primary key duplication exception:{}", ex.getMessage());@b@        return Result.fail(SystemErrorType.DUPLICATE_PRIMARY_KEY);@b@    }@b@@b@    @ExceptionHandler(value = {BaseException.class})@b@    public Result baseException(BaseException ex) {@b@        log.error("base exception:{}", ex.getMessage());@b@        return Result.fail(ex.getErrorType());@b@    }@b@@b@    @ExceptionHandler(value = {Exception.class})@b@    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)@b@    public Result exception() {@b@        return Result.fail();@b@    }@b@@b@    @ExceptionHandler(value = {Throwable.class})@b@    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)@b@    public Result throwable() {@b@        return Result.fail();@b@    }@b@}

三、自定义异常UserNotFoundException

public class UserNotFoundException extends BaseException {@b@    public UserNotFoundException() {@b@        super(OrganizationErrorType.USER_NOT_FOUND);@b@    }@b@@b@    public UserNotFoundException(String message) {@b@        super(OrganizationErrorType.USER_NOT_FOUND, message);@b@    }@b@}

四、测试接口

import com.louis.springboot.demo.exception.UserNotFoundException;@b@import org.springframework.web.bind.annotation.GetMapping;@b@import org.springframework.web.bind.annotation.RestController;@b@@b@@RestController@b@public class HelloController { @b@@b@    @GetMapping("/throwUserNotFound")@b@    public void throwUserNotFound() {@b@        throw new UserNotFoundException("user not found ");@b@    }@b@    @b@}

访问http://localhost:8000/throwUserNotFound接口,浏览器结果如下

通过Spring的@ExceptionHandler拦截处理自定义异常并标准化结果返回

另外,完整项目demo下载