Zuul学习(二)——全局异常处理
1.这里就没有用zuul的异常处理" title="异常处理">异常处理方式,而是拦截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.编写一个异常处理器
@RestControllerAdvicepublic 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);
}
}
以上是 Zuul学习(二)——全局异常处理 的全部内容, 来源链接: utcz.com/z/518665.html