springboot 全局异常统一返回

不分离使用:@ControllerAdvice+@ExceptionHandler处理全局异常

这种组合适用于前后不分离的

注解:@ControllerAdvice

 @Component 作用是将ControllerAdvice 注入到容器中

然后自定义全局异常处理类:仅用于测试使用在实际开发中根据需要指定返回数据,如果是页面,则返回String,如:return "login"

package com.wdz.boot.exception;

import com.wdz.boot.model.ResultMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler({NumberFormatException.class})
    public ResultMap numberFormatException(NumberFormatException e) {
        e.printStackTrace();
        System.out.println("数据转换异常:::" + e.getMessage());
        return ResultMap.error(e.getMessage());
    }

    @ExceptionHandler({ArithmeticException.class})
    public ResultMap arithmeticException(ArithmeticException e) {
        e.printStackTrace();
        System.out.println("运算异常:::" + e.getMessage());
        return ResultMap.error(e.getMessage());
    }

    @ExceptionHandler({NullPointerException.class})
    public ResultMap nullPointerException(NullPointerException e) {
        e.printStackTrace();
        System.out.println("空指针异常:::" + e.getMessage());
        return ResultMap.error(e.getMessage());
    }

    @ExceptionHandler({MethodArgumentTypeMismatchException.class})
    public ResultMap methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        e.printStackTrace();
        System.out.println("参数异常" + e.getMessage());
        return ResultMap.error(e.getMessage());
    }
    // 自定义异常处理
    @ExceptionHandler(TestException.class)
    public ResultMap testException(TestException e){
        return ResultMap.error(e.getMessage());
    }

}

自定义异常:

package com.wdz.boot.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
// value 指定异常错误状态码,reason 说明异常原因
@ResponseStatus(value = HttpStatus.FOUND,reason = "测试自定义异常")
public class TestException extends RuntimeException {

    public TestException(){

    }

    public TestException(String message) {
        super(message);
    }
}

如果是前后分离则使用:@RestControllerAdvice+@ExceptionHandler

在服务所在的包路径下创建项目全局异常类

package com.wdz.config;

import com.alibaba.fastjson.JSONObject;
import com.wdz.common.exception.saas.DemoException;
import com.wdz.common.resp.YzxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalException {

    @Value("${spring.application.name}")
    private String serverName;


    @ExceptionHandler(DemoException.class)
    public YzxResult handlerException(DemoException demo) {
        System.out.println(JSONObject.toJSONString(demo));
        return YzxResult.error(serverName+"出错");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public YzxResult notFount(RuntimeException e) {
        return YzxResult.error("运行时异常:" + e.getMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public YzxResult handleException(HttpRequestMethodNotSupportedException e) {
        return YzxResult.error("不支持' " + e.getMethod() + "'请求");
    }
}

自定义异常Demo

package com.wdz.common.exception.saas;

import lombok.Data;

@Data
public class DemoException extends RuntimeException {

    private static final long serialVersionUID = 6304501072268270030L;

    private String code;
    private String message;

    public DemoException(String msg) {
        this("200", msg);
    }

    public DemoException(String code, String msg) {
        super(msg);
        this.code = code;
        this.message = msg;
    }

}

测试控制器

package com.wdz.saas.controller.cli;

import com.wdz.common.exception.saas.DemoException;
import com.wdz.common.resp.YzxResult;
import com.wdz.common.utils.StringUtils;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

@Api(tags = "统一异常测试")
@RestController
@RequestMapping("/cli/course")
public class CliSaasCourseController {

    @RequestMapping(value = "demo",method = RequestMethod.POST)
    public YzxResult demo(String msg) {
        throw new DemoException("11111111111111111");
    }
}

结果:

{
  "code": "500",
  "message": "出错",
  "data": null,
  "success": false
}

message 信息可以在全局异常处理时获取,或者固定信息,直接抛不处理message

微服务下,公用全局异常不会抛出指定异常,将全局异常配置放在项目中就可以了,各管各的,有更好的方式,评论中告知谢谢

前后分离的全局异常只是返回结果的不一样,其他的一致

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值