liurunyu
5 天以前 1cf88d43994ec7ec403319032a9d118b39fe3571
pipIrr-platform/pipIrr-common/src/main/java/com/dy/common/webUtil/GlExceptionHandler.java
New file
@@ -0,0 +1,44 @@
package com.dy.common.webUtil;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 全局异常处理,处理在Controller中抛出的异常,在Controller之前(如Fileter)发生的错误或异常由GlErrorCtrl处理
 * 此类是基于拦截器和实现指定接口(GlExceptionHandler和GlExceptionHandlerImpl)
 * 另一种实现方式是基于注解切面实现(GlExceptionAspect)
 */
//此类Tag注解不起作用,即不会在swagger-ui中显示,但会在每个controler的方法返回信息中显示。
//每个controller的方法上都显示本异常API显示啰嗦,所以不启用本注解
@Hidden //在SpringDoc中隐藏本接口API
@Tag(name = "全局异常处理", description = "处理在Controller中抛出的异常,在Controller之前(如Fileter)发生的错误或异常由GlErrorCtrl处理")
//在每个controler的方法返回信息中显示下面配置信息。
@ApiResponses(@ApiResponse(
        responseCode = ResultCodeMsg.RsCode.EXCEPTION_CODE,
        description = "发生异常",
        content = {@Content(mediaType = "application/json", schema = @Schema(implementation = BaseResponse.class))}
))
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlExceptionHandler {
    @ExceptionHandler
    public BaseResponse GlExceptionHandler(GlException e){
        log.error("捕获到GlException:{}", e.getMsg(), e);
        return BaseResponseUtils.buildException(e.getMsg());
    }
    public BaseResponse exceptionHandler(Throwable t) {
        log.error("捕获到异常:{}",t.getMessage(),t);
        return BaseResponseUtils.buildException("在Controller中或后产生异常:" + t.getMessage());
    }
}