0
点赞
收藏
分享

微信扫一扫

全局异常统一返回

艾晓雪 2022-03-24 阅读 52
java

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

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.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");
    }
}

结果:

举报

相关推荐

0 条评论