SpringBoot统一异常处理

SpringBoot统一异常处理,第1张

SpringBoot统一异常处理 SpringBoot 统一异常处理 1、实现方法

通过@ControllerAdvice和@ExceptionHandler实现处理controller层的异常

@ControllerAdvice,是Spring3.2提供的新注解,它是一个Controller增强器,可对controller中被 @RequestMapping注解的方法加一些逻辑处理。最常用的就是异常处理

@ControllerAdvice
@ResponseBody  //表示返回的对象,Spring会自动把该对象进行json转化,最后写入到Response中。
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(NullPointerException.class)//表示让Spring捕获到所有抛出的SignException异常,并交由这个被注解的方法处理。
     @ResponseStatus(HttpStatus.BAD_REQUEST)  //表示设置状态码。
   	public String exceptionHandler(Exception e){
		System.out.println("发生了一个异常"+e);
       	return e.getMessage();
    }
}

统一返回结果类

public class ResponseDto {
    //错误码
    private String code;
    //提示信息
    private String msg;
    //具体的内容
    private T data;
    public ResponseDto() {
    }
    public ResponseDto(String code, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = null;
    }
    //getter和setter方法。。。
}			

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5434995.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存