javascript
springboot怎么返回404_SpringBoot(二十)_404返回统一异常处理结果
1.修改application.properties文件# 自定義404
#出現錯誤時, 直接拋出異常
spring.mvc.throw-exception-if-no-handler-found=true
#不要為我們工程中的資源文件建立映射
spring.resources.add-mappings=false
2.添加controller增強處理if (e instanceof NoHandlerFoundException) {
return ResultUtil.error(ResultEnum.NO_HANDLER_FOUND_ERROR);
}
3.測試
訪問 http://localhost:8080/hello1
// 20190705114619
// http://localhost:8080/hello1
{
"code": 404,
"msg": "接口不存在",
"data": null
}
4.完整controller增強處理類package com.kevin.common.exception;
import com.kevin.common.entity.Result;
import com.kevin.common.enums.ResultEnum;
import com.kevin.common.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.util.List;
/**
* 異常處理器
*
* @author kevin
* @date 2019/7/4 14:46
*/
@RestControllerAdvice
@Slf4j
public class KevinExceptionHandler {
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
log.error(e.getMessage(), e);
if (e instanceof KevinException) {
return ResultUtil.error(e.getMessage());
} else if (e instanceof NoHandlerFoundException) {
return ResultUtil.error(ResultEnum.NO_HANDLER_FOUND_ERROR);
} else if (e instanceof IllegalArgumentException) {
return ResultUtil.error(e.getMessage());
} else if (e instanceof IllegalStateException) {
return ResultUtil.error(e.getMessage());
} else if (e instanceof BindException) {
BindException ex = (BindException) e;
List allErrors = ex.getAllErrors();
ObjectError error = allErrors.get(0);
String defaultMessage = error.getDefaultMessage();
return ResultUtil.error(defaultMessage);
} else if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
List errors = ex.getBindingResult().getAllErrors();
String message = errors.get(0).getDefaultMessage();
return ResultUtil.error(message);
} else {
return ResultUtil.error(ResultEnum.UNKNOW_ERROR);
}
}
}
好了玩的開心
最近在整合一個springboot2.X的框架。里面就集成了這塊,有興趣的可以下載下來看看
地址:https://github.com/FunCodingOfWe/kevin-boot
歡迎start
總結
以上是生活随笔為你收集整理的springboot怎么返回404_SpringBoot(二十)_404返回统一异常处理结果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 路由器在家怎么和猫一起用如何使用路由器和
- 下一篇: springboot java获取版本号