全局异常捕获

Spring和SpringBoot中设置全局异常

一、设置全局异常捕获

捕获Controller层(未捕获)的异常,Service的抛出(throw)的异常在没有处理也会抛给Controller层从而被捕获

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ustcinfo.tCloud3.domain.Result;

/**
 * 全局异常处理: 处理Controller层未捕获(往外抛)的异常并返回结果到界面
 * 注:往外抛异常会终止程序运行
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    // value:异常类型(RuntimeException、NullPointerException、Exception ...)
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<Object> handle(Exception e) {
        e.printStackTrace();
        return new Result<Object>().error(-1, e.getMessage());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35959573/article/details/81017897
今日推荐