Springboot异常统一处理

在一个项目之中,我们经常会遇到一些异常,基本上属于运行期异常,这种异常如果不做处理的话就会返回给用户,会显得很不友好,我们可以写一个异常看看,代码如下

package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class DemoA {


    @RequestMapping(value ="test", method = RequestMethod.GET)
    public String test(HttpServletRequest req, String aaaa, HttpSession m){
     throw  new RuntimeException("java.lang.的一个异常");
    }
}

这里出现了一个乱码,不过这个无所谓,这样是不是很难看?

可能有的朋友会说,写代码的时候回注意着,把所有的代码都try起来,还有测试等等,但其实并不是这样

有的时候我们必须要抛出异常,触发代码的熔断机制,比如for循环里面访问数据库添加数据,前面成功了,后面的数据本身有异常怎么办?

我们需要回滚,而回滚就需要抛出异常才会回滚,这个时候我们就需要手动的throw一个异常了

那么如何做异常统一处理呢?

首先我们还是先创建一个类,代码如下

package com.example.demo;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionHandle{
		/**
		 * 异常拦截
		 * */
	  @ExceptionHandler(value = Exception.class)
      @ResponseBody
      public String exceptionGet(Exception ex){
            
			return "出错啦";
		
      }
  }  
  

@ControllerAdvice这个注解告诉springboot,这个类是我们的异常处理类

@ExceptionHandler这个注解是我们要捕获的异常,参数是异常的class字节码,我们来看一下源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
    Class<? extends Throwable>[] value() default {};
}

 

一个未知的字节码文件,必须继承自Throwable,而且是数组,说明我们可以捕获多个异常,就相当于catch里面的参数

不过我们这里直接捕获Exception就可以了,

@ResponseBody注解代表我们返回json

我们在测试一下

这样就成功了,我们可以根据错误的不同返回不同的信息,比如说账号或密码不可为空,权限不足等等

 

源码地址:https://gitee.com/ww2510095/springboot_learning

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值