SpringBoot统一收集异常信息并返回给前端

目录

适用场景

实现方法

结合Servlet对象

@RestControllerAdvice


适用场景

通常前后端交互时,后端对前端参数进行校验后,对于校验不通过的信息会自定义一个异常抛出,但是后端一旦抛出异常,后台接口服务就会报500的错误

对于有些逻辑错误而言,我们只是想将此信息提示给用户,这时候我们需要将抛出来的异常进行捕获,然后封装成提示信息返回给前端,最常见的就是try catch。

@RequestMapping("/test")
    public String test() {
        try {
            throw new RuntimeException("出错了。。。。");
        }catch (Exception ex){
            return ex.getMessage();
        }
    }

 与前端的交互在controller层,也就意味着我们每个controller方法都要加一个try catch,这样太冗余了,所以我们采用一个统一收集处理异常的方法,来将异常返回。

实现方法

SpringBoot提供了一个很好用的注解,@RestControllerAdvice @ExceptionHandler

package com.example.springboot;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class CommonController {
    @ExceptionHandler(Exception.class)
    public String handleException(Exception ex) {
        return ex.getMessage();
    }
}

我们增加了一个统一处理前端返回信息的类,即便业务controller方法里面没有try catch,还是可以通过@ExceptionHandler进行捕获并返回(这里指定的是所有异常Exception,可以根据不同异常的返回结果,进行细化处理)。

结合Servlet对象

上述示例只是简单返回一个字符串,通常在项目里,我们是通过HttpServletRequest对象HttpServletResponse对象来接收和返回数据的,我们同样可以在异常捕获方法上增加相应的参数,保证和业务处理方法的一致性。

package com.example.springboot;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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


@RestControllerAdvice
public class CommonController {
   
    /**
     * 对各种异常统一返回
     */
    @ExceptionHandler(value = Exception.class)
    public void index(HttpServletRequest request, HttpServletResponse response,Exception ex) {
        //将返回信息写入response
    }
}

@RestControllerAdvice

@RestControllerAdvice对异常处理只是其中一个作用,注解了@RestControllerAdvice的类的方法可以使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上。

@InitBinder可以对WebDataBinder对象进行初始化,在前后端交互时,经常会遇到表单中的日期字符串和JavaBean的Date类型的转换,通过这个方法可以对前端穿过来的日期字符串进行统一的格式化处理,无需在每个方法中进行转换。

@ModelAttribute主要的作用是将数据添加到模型对象中。

    @RequestMapping("/hello")
    public String hello(Model model) {

        return model.getAttribute("attributeName").toString();
    }
package com.example.springboot;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

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


@RestControllerAdvice
public class CommonController {

    @ModelAttribute
    public void populateModel(Model model) {
        model.addAttribute("attributeName", "统一返回");
    }


}

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值