Spring-Boot 统一异常处理

下图列出了Spring Boot中跟MVC异常处理相关的类:


Spring Boot在启动过程中会根据当前环境进行AutoConfiguration。

EmbeddedServletContainerCustomizer类可以设置错误请求,当报出内部异常时候如:404找不到,500服务器内部错误的时候,会进行相应的处理。

package com.lgy.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import com.lgy.web.controller.TestController;

@Configuration
public class ErrorPageConfig {
	public static Logger logger = LoggerFactory.getLogger(TestController.class);
	@Bean
	public EmbeddedServletContainerCustomizer containerCustomizer() {
		return (ConfigurableEmbeddedServletContainer container) -> {
			/**
			 * 页面异常错误
			 */
			container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));
		    container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500"));
		};
	}
	
}

自定义异常:

package com.lgy.web.controller.exception;

public class FormRepeatException extends Exception  {
	private static final long serialVersionUID = -9079010183705787652L;
	public FormRepeatException() {
	}
	public FormRepeatException(String message) {        //用来创建指定参数对象
        super(message);                             //调用超类构造器
    }
}

在Controller层中获取异常信息:

继承DefaultErrorAttributes值。

package com.lgy.web.controller.exception;

import java.util.Map;


import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 
 * <p>Title: PageErrorController</p>  
 * <p>Description: 页面异常进行处理</p>  
 * @date 2016年1月21日
 */
@Controller
public class PageErrorController extends DefaultErrorAttributes   {


	@RequestMapping("/404")
	public String aaa404() {
		RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
		Map<String, Object> body = this.getErrorAttributes(requestAttr, false);
		
		System.out.println(body);
		return "404";
	}
	
	@RequestMapping("/500")
	public String assaa404() {
		RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
		Map<String, Object> body = this.getErrorAttributes(requestAttr, false);
		
		System.out.println(body);
		return "500";
	}



	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值