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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值