Zuul学习(二)——全局异常处理

1.这里就没有用zuul的异常处理方式,而是拦截controller的异常,创建一个公共的模块common,其它模块引入该依赖即可

2.编写统一的异常类

public class GlobalException extends RuntimeException {

    private static final long serialVersionUID = 1L;
    private Integer code;
    private String msg;

    public GlobalException(Integer code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

3.编写一个异常处理器

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        e.printStackTrace();
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return new Result<>(ex.getCode(), ex.getMsg());
        } else {
            return new Result<>(500, "系统错误");
        }
    }

}

4.如果引入了common的依赖,异常拦截无效的话,尝试在当前的模块的启动类扫描对应的包路径(比如在user-service模块)

@SpringBootApplication(scanBasePackages = "com.carter.*")
@EnableEurekaClient
public class ThymeleafApplication {

    public static void main(String[] args) {
        SpringApplication.run(ThymeleafApplication.class, args);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章