【springboot】全局异常处理

导读:本篇文章讲解 【springboot】全局异常处理,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一.问题说明

1.后端异常后,接口仍以固定数据格式返回数据
2.适合于前后端分离开发

二.测试结果

在这里插入图片描述

三.代码示例

1.定义一个实体类

package com.learning.utils;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @Author wangyouhui
 * @Description 实体类
 **/
@Data
@AllArgsConstructor
public class R<T> {
    private String code;
    private Boolean success;
    private String msg;
    private T data;

    public static R data(Object result) {
        return new R("200", true, "", result);
    }

    public static R fail(String message) {
        return new R("500", false, message, null);
    }
}

2.定义一个接口

package com.learning.controller;

import com.learning.utils.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author wangyouhui
 * @Description 测试接口异常统一处理
 **/
@RestController
@RequestMapping("exception")
public class ExceptionController {

    @GetMapping("/get")
    public R<String> get(){
        String result = "hello";
        return R.data(result);
    }

    @GetMapping("/error")
    public R<String> error(){
        String result = "hello";
        int a = 1/0;
        return R.data(result);
    }

}

3.定义一个ControllerAdvice

package com.learning.advice;

import com.learning.utils.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author wangyouhui
 * @Description 对所有Controller拦截增强
 **/
@RestControllerAdvice
public class ExceptionAdvice {
    @ExceptionHandler
    public R handleException(Exception e){
    	//将异常打印出来,以防捕获后不抛异常找不到错误所在
        e.printStackTrace();
        return R.fail(e.getMessage());
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/92351.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!