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

 

你可能感兴趣的:(Spring,Boot)