SpringBoot入门(15)- SpringBoot 中异常处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangminemail/article/details/82924870

1、去掉springBoot中默认的异常处理类

@SpringBootApplication(exclude=ErrorMvcAutoConfiguration.class)
public class App {
	public static void main(String[] args) {
		ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
//		HandlerInterceptor
	}
}

2、全局异常处理的两种方式

方式一:实现异常注册类ErrorPageRegistrar,重写registerErrorPages接口

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

@Component
public class CommonErrorRegistry implements ErrorPageRegistrar {

	@Override
	public void registerErrorPages(ErrorPageRegistry registry) {
		
		ErrorPage e404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
		ErrorPage e500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
		ErrorPage nullp = new ErrorPage(NullPointerException.class, "/null.html");
		registry.addErrorPages(e404, e500, nullp);
	}
	

}

方式二:使用注解的方式,主要用到类注解@ControllerAdvice,接口注解@ExceptionHandler

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

@ControllerAdvice
public class GolbalExeptionhandler {

	@ExceptionHandler(value=Exception.class)
	@ResponseBody
	public String errorHandler(Exception e){
		return "global error " + e.getClass().getName();
	}
}

3、局部异常处理

主要用到方法注解 @ExceptionHandler

import java.io.FileNotFoundException;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BookRest {
	
	@ExceptionHandler(Exception.class)
	public String error(Exception e){
		return "found exception "+e.getMessage();
	}

	@GetMapping("/book/error1")
	public String error1() throws FileNotFoundException{
		throw new FileNotFoundException("file not found");
	}
	
	@GetMapping("/book/error2")
	public String error2() throws ClassNotFoundException{
		throw new ClassNotFoundException("class not found");
	}
	
	
}

猜你喜欢

转载自blog.csdn.net/zhangminemail/article/details/82924870
今日推荐