Administrator
2024-01-30 bc45a4a5a9b40e934317644c691ec5117e802859
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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());
    }
}