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

本文详细介绍了如何在SpringBoot中自定义异常处理,包括移除默认异常处理器、全局异常处理的两种方法以及局部异常处理的实践。通过实现ErrorPageRegistrar接口或使用@ControllerAdvice注解,开发者可以更灵活地控制应用的错误页面展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值