アプリケーション開発-web春ブーツチュートリアル(6) - エラー処理

エラー処理

      方法A:春ブートデフォルトマッピング/エラーにすべてのエラー、(メソッドを達成するために本明細書に記載)での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();
	}

}

   その後、カスタムエラーページerror.htmlを作成し、フォルダを作成templasの下にエラーを追加

<!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>

 プロジェクトの訪問にテンプレートページを起動します。

アクセス権:

エラー訪問:

方法2:使用し@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