SpringBoot之自定义异常的两种方式-yellowcong

Springboot异常的处理,可以通过一下几种方法,1、使用@ControllerAdvice来进行统一异常处理,@ExceptionHandler(value = Exception.class)来指定捕获的异常 ;2、通过自定义BasicErrorController 错误处理,这个是处理是基于状态码的。

代码地址

https://gitee.com/yellowcong/springboot-demo/tree/master/springboot-json

目录结构

这里写图片描述

1、通过@ControllerAdvice

通过使用@ControllerAdvice来进行统一异常处理,@ExceptionHandler(value = Exception.class)来指定捕获的异常 ,这个异常的处理,是全局的,所有类似的异常,都会跑到这个地方处理

package com.yellowcong.exception;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

/**
 * 创建日期:2018年4月6日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:<br/>
 */
@ControllerAdvice
public class RestExceptionHandler {

    /**
     * 创建日期:2018年4月6日<br/>
     * 代码创建:黄聪<br/>
     * 功能描述:直接处理 HttpMessageNotReadableException 报错的信息<br/>
     * @param ex
     * @return
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    @ResponseBody
    public String requestNotReadable(HttpMessageNotReadableException ex){
        ex.printStackTrace();
        //json 数据读取失败
        JSONObject result = new JSONObject();
        result.put("code", 400);
        result.put("msg", "json data is error ");

        return result.toJSONString();
    }

}

测试

当我们发送错误的json数据后,直接报错,而且这个错误并不是非常的友好,所以我们需要自定义异常来解决这个问题。
这里写图片描述

通过自定义错误后,解决的效果,返回的是自定义的错误消息,这种效果好多了。
这里写图片描述

2、自定义BasicErrorController 错误处理

2.1启动器添加EmbeddedServletContainerCustomizer

在启动器里面,添加EmbeddedServletContainerCustomizer,然后在里面注册处理相应状态码的界面

package com.yellowcong;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;

@SpringBootApplication
public class ConfigMain {

    public static void main(String[] args) {
        SpringApplication.run(ConfigMain.class, args);
    }

    /**
     * 创建日期:2018年4月6日<br/>
     * 代码创建:黄聪<br/>
     * 功能描述:错误的处理 <br/>
     * @return
     */
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer(){
        return new EmbeddedServletContainerCustomizer(){
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                //404
                container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
                //500错误
                container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
                //400错误
                container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/error/json"));
            }
        };
    }


}

2.2错误处理控制器

这个控制器,和普通的控制器类似,没有啥特别的,主要是用来处理状态吗对应的错误的视图,这个地方需要说明的一点,json的404错误和直接通过浏览器访问的404两个的效果是不一样的。

package com.yellowcong.error;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

/**
 * 创建日期:2018年4月6日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:<br/>
 */
@Controller
@RequestMapping(value = "/error")
public class ExceptionController {

    @RequestMapping(value = "/404")
    @ResponseBody
    public String error404(HttpServletRequest request) {
        //json 数据读取失败
        JSONObject result = new JSONObject();
        result.put("code", 404);
        result.put("msg", "Page not found ");
        result.put("method", "error404");
        return result.toJSONString();
    }


    /**
     * 创建日期:2018年4月6日<br/>
     * 代码创建:黄聪<br/>
     * 功能描述:produces 表示只处理网页直接发送的请求<br/>
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(produces = "text/html", value = "/404")
    @ResponseBody
    public String errorHtml404(HttpServletRequest request, HttpServletResponse response) {
        //跳转到error 目录下的 404模板
        return "界面没有找到!!!";
    }

    /**
     * 创建日期:2018年4月6日<br/>
     * 代码创建:黄聪<br/>
     * 功能描述:json读取有问题的情况<br/>
     * @param request
     * @return
     */
    @RequestMapping(value = "/json",produces="application/json;charset=UTF-8")
    @ResponseBody
    public String errorJson() {
        //json 数据读取失败
        JSONObject result = new JSONObject();
        result.put("code", 400);
        result.put("msg", "json data is error ");
        result.put("method", "errorJson");
        return result.toJSONString();
    }

}

测试结果

测试中,我访问的json错误,提示json有问题,当我直接通过josn访问没有的界面的时候,提示没有找到,当直接通过浏览器访问没有找到的界面的时候,直接显示的没有找到,但是是我们的html的响应消息。
这里写图片描述

参考文章

https://blog.csdn.net/king_is_everyone/article/details/53080851
https://www.cnblogs.com/nosqlcoco/p/5562107.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狂飙的yellowcong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值