返回给前端异常的处理

时间:2024-6-18    作者:老大夫    分类: SpringCloud


建立全局异常处理

exp.GlobalExceptionHandler.java

实际也是一个controller,出现异常报错就会跳转到这个controller中

package com.atguigu.cloud.exp;

import com.atguigu.cloud.resp.ResultData;
import com.atguigu.cloud.resp.ReturnCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData<String> exception(Exception e){
        System.out.println("######## come in GlobalExceptionHandler");
        log.error("全局异常信息:{}",e.getMessage(),e);
        return ResultData.fail(ReturnCodeEnum.RC500.getCode(), e.getMessage());
    }
}

方式二:自己在controller的方法里写try catch


    @GetMapping("error")
    public ResultData<Integer> getPayError() {
        Integer i = Integer.valueOf(200);

        try {
            System.out.println("com in try catch");
            int age=10/0;
        }catch (Exception e){
            e.printStackTrace();
            return ResultData.fail(ReturnCodeEnum.RC500.getCode(), e.getMessage());
        }
        return ResultData.success(i);
    }


扫描二维码,在手机上阅读

推荐阅读: