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);
}
}