Spring Boot教程(6)-web应用开发-错误处理

错误的处理

      方法一:Spring Boot 将所有的错误默认映射到/error, 实现ErrorController(本文以方法一实现)

package com.wsj.springbootdemo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("error")
public class BaseErrorController implements ErrorController {
private static final Logger logger = LoggerFactory.getLogger(BaseErrorController.class);

	public String getErrorPath() {
		logger.info("出错啦!进入自定义错误控制器");
		return "error/error.html";
	}

	@RequestMapping
	public String error() {
		return getErrorPath();
	}

}

   添加templas下创建error文件夹,然后创建error.html自定义的错误页面

<!DOCTYPE html>
<html lang="zh">
<head>
    <title>boot-error</title>
</head>
<body class="gray-bg">
<div class="middle-box text-center animated fadeInDown">
    <h1>500</h1>
    <h3 class="font-bold">系统出错,请联系管理员</h3>
</div>
</body>
</html>

 启动项目访问上一节的template页面:

正确访问:

错误访问:

方法二:使用注解@ControllerAdvice可以自己测试。。。

/**

 * 统一异常处理

 *

 * @param exception

 *            exception

 * @return

 */

@ExceptionHandler({ RuntimeException.class })

@ResponseStatus(HttpStatus.OK)

public ModelAndView processException(RuntimeException exception) {

     logger.info("自定义异常处理-RuntimeException");

     ModelAndView m = new ModelAndView();

     m.addObject("roncooException", exception.getMessage());

     m.setViewName("error/500");

     return m;

}



/**

 * 统一异常处理

 *

 * @param exception

 *            exception

 * @return

 */

@ExceptionHandler({ Exception.class })

@ResponseStatus(HttpStatus.OK)

public ModelAndView processException(Exception exception) {

     logger.info("自定义异常处理-Exception");

     ModelAndView m = new ModelAndView();

     m.addObject("roncooException", exception.getMessage());

     m.setViewName("error/500");

     return m;

}

github地址:https://github.com/itwsj/springbootdemo

发布了210 篇原创文章 · 获赞 1042 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/onceing/article/details/104335993
今日推荐