Spring Boot 异常处理

1.去掉Spring Boot默认的异常处理逻辑exclude=ErrorMvcAutoConfiguration.class

package vip.fkandy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;

@SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class)
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

2.写一个类实现ErrorPageRegistrar接口,重写registerErrorPages方法设置错误跳转页面,在该方法里面,添加具体的错误逻辑(类似于web.xml里面配置错误处理方法)

package vip.fkandy;

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 CommonErrorPageRegistry 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 illegalArgument = new ErrorPage(IllegalArgumentException.class, "/args.html");
		registry.addErrorPages(e404, e500, illegalArgument);
	}
}

全局异常处理

  1. 需要注释掉上文中的CommonErrorPageRegistry

  2. 当前类生效的异常处理

package vip.fkandy;

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 BookController {

	
	@ExceptionHandler(value = Exception.class)
	public String error(Exception e) {
		return "file not found exception" + e.getMessage();
	}

	@GetMapping(value = "/book/list")
	public String list() throws FileNotFoundException {
		throw new FileNotFoundException("file not found");
	}
}

全局生效的异常处理

package vip.fkandy;

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

/**
 * 全局异常处理
 * 
 * @author chenjianfei
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public String error(Exception e) {
		return "global exception:" + e.getMessage();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值