Spring MVC @ExceptionHandler示例

在本教程中,我们向您展示如何在Spring MVC框架中进行异常处理。 通常,我们使用@ExceptionHandler来决定如果引发某些异常,应该返回哪个“视图”。

PS此@ExceptionHandler类从Spring 3.0开始可用

1.项目结构

查看项目目录结构(标准的Maven项目)。

目录结构

2.自定义例外

具有自定义错误代码和错误描述的自定义异常。

CustomGenericException.java
package com.mkyong.web.exception;

public class CustomGenericException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	private String errCode;
	private String errMsg;

	public String getErrCode() {
		return errCode;
	}

	public void setErrCode(String errCode) {
		this.errCode = errCode;
	}

	public String getErrMsg() {
		return errMsg;
	}

	public void setErrMsg(String errMsg) {
		this.errMsg = errMsg;
	}

	public CustomGenericException(String errCode, String errMsg) {
		this.errCode = errCode;
		this.errMsg = errMsg;
	}

}

3.弹簧控制器

Spring控制器,请查看以下执行流程:

  1. 如果用户提供一个/error请求,它将引发“ CustomGenericException”,并且将handleCustomException()方法。
  2. 如果用户提供一个/io-error请求,它将引发“ IOException”,并且将handleAllException()方法。
MainController.java
package com.mkyong.web.controller;

import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.mkyong.web.exception.CustomGenericException;

@Controller
public class MainController {

	@RequestMapping(value = "/{type:.+}", method = RequestMethod.GET)
	public ModelAndView getPages(@PathVariable("type") String type)
		throws Exception {

	  if ("error".equals(type)) {
		// go handleCustomException
		throw new CustomGenericException("E888", "This is custom message");
	  } else if ("io-error".equals(type)) {
		// go handleAllException
		throw new IOException();
	  } else {
		return new ModelAndView("index").addObject("msg", type);
	  }

	}

	@ExceptionHandler(CustomGenericException.class)
	public ModelAndView handleCustomException(CustomGenericException ex) {

		ModelAndView model = new ModelAndView("error/generic_error");
		model.addObject("errCode", ex.getErrCode());
		model.addObject("errMsg", ex.getErrMsg());

		return model;

	}

	@ExceptionHandler(Exception.class)
	public ModelAndView handleAllException(Exception ex) {

		ModelAndView model = new ModelAndView("error/generic_error");
		model.addObject("errMsg", "this is Exception.class");

		return model;

	}

}

4. JSP页面

pages/index.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
	<h2>Spring MVC @ExceptionHandler Example</h2>

	<c:if test="${not empty msg}">
		<h2>${msg}</h2>
	</c:if>
	
</body>
</html>
pages/error/generic_error.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>

	<c:if test="${not empty errCode}">
		<h1>${errCode} : System Errors</h1>
	</c:if>
	
	<c:if test="${empty errCode}">
		<h1>System Errors</h1>
	</c:if>

	<c:if test="${not empty errMsg}">
		<h2>${errMsg}</h2>
	</c:if>
	
</body>
</html>

5.测试

查看以下3个测试用例:

1. http:// localhost:8080 / SpringMvcExample /任何内容

弹簧异常处理结果正常

2. http:// localhost:8080 / SpringMvcExample / error

春天异常处理结果错误

3. http:// localhost:8080 / SpringMvcExample / io-error

春天异常处理结果错误

6. @ControllerAdvice示例

上面的@ExceptionHandler示例仅适用于单个控制器,要全局应用(所有控制器),请使用@ControllerAdvice注释类。

GlobalExceptionController.java
package com.mkyong.web.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import com.mkyong.web.exception.CustomGenericException;

@ControllerAdvice
public class GlobalExceptionController {

	@ExceptionHandler(CustomGenericException.class)
	public ModelAndView handleCustomException(CustomGenericException ex) {

		ModelAndView model = new ModelAndView("error/generic_error");
		model.addObject("errCode", ex.getErrCode());
		model.addObject("errMsg", ex.getErrMsg());

		return model;

	}

	@ExceptionHandler(Exception.class)
	public ModelAndView handleAllException(Exception ex) {

		ModelAndView model = new ModelAndView("error/generic_error");
		model.addObject("errMsg", "this is Exception.class");

		return model;

	}
	
}

7.下载源代码

下载– SpringMvc-ExceptionHandler-Example.zip (15 KB)

参考文献

  1. Spring @ExceptionHandler JavaDoc
  2. Spring @ControllerAdvice JavaDoc
  3. Spring MVC异常处理示例

翻译自: https://mkyong.com/spring-mvc/spring-mvc-exceptionhandler-example/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值