美文网首页架构
spring项目结构设计-全局异常处理

spring项目结构设计-全局异常处理

作者: jinelei | 来源:发表于2020-05-13 17:13 被阅读0次

    spring全局异常处理使用注解RestControllerAdviceControllerAdvice

    • BindExceptionMethodArgumentNotValidException是hibernate校验失败抛出的异常。
    • BasicException是自定义的全局统一异常,其中属性error可以提取出异常信息。
    @RestControllerAdvice
    public class BassExceptionHandler {
        private static final Logger logger = LoggerFactory.getLogger(BassExceptionHandler.class);
    
        @ExceptionHandler(value = BindException.class)
        @ResponseStatus(value = HttpStatus.BAD_REQUEST, code = HttpStatus.BAD_REQUEST)
        public BassResult<String> handleBadParam(BindException ex) {
            logger.error(ex.getMessage());
            String result = ex.getBindingResult().getAllErrors().parallelStream().map(object -> object.getDefaultMessage())
                    .collect(Collectors.joining(", "));
            return new BassResult<String>().builder().error(BassError.BAD_PARAM, result).build();
        }
    
        @ExceptionHandler(value = MethodArgumentNotValidException.class)
        @ResponseStatus(value = HttpStatus.BAD_REQUEST, code = HttpStatus.BAD_REQUEST)
        public BassResult<String> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
            logger.error(ex.getMessage());
            String result = ex.getBindingResult().getAllErrors().parallelStream().map(object -> object.getDefaultMessage())
                    .collect(Collectors.joining(", "));
            return new BassResult<String>().builder().error(BassError.BAD_PARAM, result).build();
        }
    
        @ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
        @ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE, code = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
        public BassResult<String> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex) {
            logger.error(ex.getMessage());
            return new BassResult<String>().builder().error(BassError.UNSUPPORTED_MEDIA_TYPE, ex.getMessage()).build();
        }
    
        @ExceptionHandler(value = BassException.class)
        @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, code = HttpStatus.INTERNAL_SERVER_ERROR)
        public BassResult<String> handleBasicException(BassException ex) {
            logger.error(ex.toString());
            return new BassResult<String>().builder().error(ex.getError(), ex.getMessage()).build();
        }
    
        @ExceptionHandler(value = Exception.class)
        @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, code = HttpStatus.INTERNAL_SERVER_ERROR)
        public BassResult<String> handleException(Exception ex) {
            logger.error(ex.getMessage());
            return new BassResult<String>().builder().error(BassError.INTERNAL_SERVER_ERROR, ex.getMessage()).build();
        }
    }
    

    相关文章

      网友评论

        本文标题:spring项目结构设计-全局异常处理

        本文链接:https://www.haomeiwen.com/subject/evxonhtx.html