Spring Boot Tutorial (6) -web Application Development - Error Handling

Error handling

      Method a: Spring Boot all errors to the default mapping / error, achieve ErrorController in (a method described herein to achieve)

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

}

   Add error under templas create a folder, then create a custom error page 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>

 Start on a project visit the template page:

The right to access:

Error visit:

Method Two: Use annotations @ControllerAdvice can test yourself. . .

/**

 * 统一异常处理

 *

 * @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 Address: https://github.com/itwsj/springbootdemo

Published 210 original articles · won praise 1042 · Views 560,000 +

Guess you like

Origin blog.csdn.net/onceing/article/details/104335993