springboot全局异常处理器捕获全局异常

package com.example.tlias.exception;

import com.example.tlias.Resource.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/*定义全局异常处理类 只要出现异常就能捕获
@RestControllerAdvice = @ControllerAdvice + @ResponseBody会将本类方法自动转换成json格式 */
@RestControllerAdvice
@Slf4j
public class buhuoyicahng {

    //定义要捕获的异常  Exception.class 表示捕获所有异常
    @ExceptionHandler(Exception.class)
    //Exception ex 定义异常类 出现异常是提示错误状态码
    public Result Tryexception(Exception ex) {
        //ex.printStackTrace(); 提示错误状态码
        ex.printStackTrace();
        log.info("出异常了");
        //向前端返回错信息
        return Result.error("操作失败,请联系程序员改代码");

    }


}

你可能感兴趣的:(spring,boot,后端,java)