配置全局advice
@RestControllerAdvice
public class GlobalAdvice {
/**
* 處理404,記得配置yaml
*/
@ExceptionHandler(NoHandlerFoundException.class)
public BaseCommonResult<String> handlerNoFoundException(Exception e)
{
return BaseCommonResult.failed(ResultCode.PageNotFound);
}
}
配置application.yaml
注意,關閉資源映射會導致swagger失效,要在MvcConfig中放行swagger資源
spring:
mvc:
### 讓mvc直接拋出異常,在全局異常類,捕獲404 異常的類 NoHandlerFoundException.class
throw-exception-if-no-handler-found: true
### 關閉資源映射
resources:
add-mappings: false