springboot学习笔记3(全局错误页面配置)

前言     

     在生产中,web程序后台处理异常报错,页面显示异常信息,这对用户来说非常不友好。springboot默认提供了对所有异常处理方法,针对服务客户端,以json格式返回异常信息,响应状态码;对浏览器客户端,响应一个单一的提示页面。springboot也提供了多个我们可选择可配置的异常处理解决方案。下面就简单的介绍一种方式。

   

  定义异常页面


          不同的异常,客户端会返回不同的http响应状态码:(404,403,500等)。我们可以定义以这些状态码为名字的文件名:404.html.500.html。服务的响应异常时候,就会跳转到对应状态码的页面。这些页面必须在error目录下:

springboot学习笔记3(全局错误页面配置)_第1张图片springboot学习笔记3(全局错误页面配置)_第2张图片

在定义一个404.html页面,然后在浏览器随便输入一个地址:localhost:8080/test/test...(如上图)

 2.对于restful风格,请求返回的都是json格式数据。我们可以在这样定义一个类

@ControllerAdvice(basePackages = "com.test")
public class AdviceConfigurer extends ResponseEntityExceptionHandler {
        @ExceptionHandler({ Exception.class })
	@ResponseBody
	ResponseEntity handleControllerException(HttpServletRequest request, Throwable ex) {
		HttpStatus status = getStatus(request);
		Map map = new HashMap();
	       #状态码
               map.put("status", status.value());
	      #标识失败
               map.put("flag", "01");
	       #异常信息
               map.put("message", ex.getMessage());

		return new ResponseEntity<>(map, status);
	}

	private HttpStatus getStatus(HttpServletRequest request) {
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		if (statusCode == null) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
		return HttpStatus.valueOf(statusCode);
	}
}


测试

定义一个Controller类

@RestController public class TestController {
   @Resource
    private PersonRepository  personRepository;  

	@GetMapping(value = "/test")
	public Person test(){
		String s=null;
		Person p = personRepository.findOne(s);
		return p;
	}

浏览器中访问


springboot学习笔记3(全局错误页面配置)_第3张图片


你可能感兴趣的:(springboot)