zoukankan      html  css  js  c++  java
  • spring boot GlobalExceptionHandler @RestControllerAdvice @ExceptionHandler

    package me.zhengjie.common.exception.handler;
    
    import lombok.extern.slf4j.Slf4j;
    import me.zhengjie.common.exception.BadRequestException;
    import me.zhengjie.common.exception.EntityExistException;
    import me.zhengjie.common.exception.EntityNotFoundException;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.security.access.AccessDeniedException;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import static org.springframework.http.HttpStatus.BAD_REQUEST;
    import static org.springframework.http.HttpStatus.FORBIDDEN;
    import static org.springframework.http.HttpStatus.NOT_FOUND;
    
    /**
     * @author jie
     * @date 2018-11-23
     */
    @Slf4j
    @RestControllerAdvice
    public class GlobalExceptionHandler {
    
        /**
         * 处理所有不可知的异常
         * @param e
         * @return
         */
        @ExceptionHandler(Exception.class)
        public ResponseEntity handleException(Exception e){
            // 打印堆栈信息
            log.error(getStackTrace(e));
            ApiError apiError = new ApiError(BAD_REQUEST.value(),e.getMessage());
            return buildResponseEntity(apiError);
        }
    
        /**
         * 处理 接口无权访问异常AccessDeniedException
         * @param e
         * @return
         */
        @ExceptionHandler(AccessDeniedException.class)
        public ResponseEntity handleAccessDeniedException(AccessDeniedException e){
            // 打印堆栈信息
            log.error(getStackTrace(e));
            ApiError apiError = new ApiError(FORBIDDEN.value(),e.getMessage());
            return buildResponseEntity(apiError);
        }
    
        /**
         * 处理自定义异常
         * @param e
         * @return
         */
        @ExceptionHandler(value = BadRequestException.class)
        public ResponseEntity<ApiError> badRequestException(BadRequestException e) {
            // 打印堆栈信息
            log.error(getStackTrace(e));
            ApiError apiError = new ApiError(e.getStatus(),e.getMessage());
            return buildResponseEntity(apiError);
        }
    
        /**
         * 处理 EntityExist
         * @param e
         * @return
         */
        @ExceptionHandler(value = EntityExistException.class)
        public ResponseEntity<ApiError> entityExistException(EntityExistException e) {
            // 打印堆栈信息
            log.error(getStackTrace(e));
            ApiError apiError = new ApiError(BAD_REQUEST.value(),e.getMessage());
            return buildResponseEntity(apiError);
        }
    
        /**
         * 处理 EntityNotFound
         * @param e
         * @return
         */
        @ExceptionHandler(value = EntityNotFoundException.class)
        public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) {
            // 打印堆栈信息
            log.error(getStackTrace(e));
            ApiError apiError = new ApiError(NOT_FOUND.value(),e.getMessage());
            return buildResponseEntity(apiError);
        }
    
        /**
         * 处理所有接口数据验证异常
         * @param e
         * @returns
         */
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
            // 打印堆栈信息
            log.error(getStackTrace(e));
            String[] str = e.getBindingResult().getAllErrors().get(0).getCodes()[1].split("\.");
            StringBuffer msg = new StringBuffer(str[1]+":");
            msg.append(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            ApiError apiError = new ApiError(BAD_REQUEST.value(),msg.toString());
            return buildResponseEntity(apiError);
        }
    
        /**
         * 统一返回
         * @param apiError
         * @return
         */
        private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
            return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));
        }
    
        /**
         * 获取堆栈信息
         * @param throwable
         * @return
         */
        private String getStackTrace(Throwable throwable)
        {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            try {
                throwable.printStackTrace(pw);
                return "
    "+sw.toString();
            } finally {
                pw.close();
            }
        }
    }
    package me.zhengjie.common.exception.handler;
    
    import com.fasterxml.jackson.annotation.JsonFormat;
    import lombok.Data;
    import java.time.LocalDateTime;
    
    /**
     * @author jie
     * @date 2018-11-23
     */
    @Data
    class ApiError {
    
        private Integer status;
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime timestamp;
        private String message;
    
        private ApiError() {
            timestamp = LocalDateTime.now();
        }
    
        public ApiError(Integer status,String message) {
            this();
            this.status = status;
            this.message = message;
        }
    }
  • 相关阅读:
    一次线上问题引发的对于C#中相等判断的思考
    Node中的模块引入机制
    Node 各个版本支持ES2015特性的网站
    使用Chrome 中的 ssh 插件登陆 linux 服务器
    vmWare 虚机文件不能启动的事故处理
    JaveScript 中使用 XSLT转换XML文档
    浏览器上的坐标体系相关概念(客户区,页面,屏幕)
    visual Studio 中使用正则表达式来进行查找替换
    JavaScript 执行环境及作用域
    Laravel save部分字段失效的bug问题解决
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/11220298.html
Copyright © 2011-2022 走看看