一、自定义异常
这里不做Spring MVC基本说明和简单配置,直接进入异常处理环节。
自定义异常类用于系统内部已经识别的异常,提前做好了应对这类异常的准备,类文件如下:
package com.dasheng.util; public class MySystemException extends Exception { private static final long serialVersionUID = 7775604244452461918L; private String message; public MySystemException() { } public MySystemException(String message) { super(message); this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
如果有多个自定义的异常类,可以通过继承,灵活进行控制。
二、实现异常处理类
通过Spring MVC的注解@ControllerAdvice 实现自动加载bean,IOC的精华。。
注解@ExceptionHandler用来指定所需处理的异常类型;@ResponseBody用来指定数据放回的方式。实现如下:
package com.dasheng.util; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public @ResponseBody String handleException(HttpServletRequest request, Exception ex) { String message = null; if (ex instanceof MySystemException) { message = ((MySystemException) ex).getMessage(); } else { message = "{'message':'system error, connect developer'}"; } HLogger.error(ex); return message; } }
三、产生异常并测试
Spring MVC REST 服务方式,进行测试,获取JSON对象中不存在的key时抛出JSONException,被上面定义的GlobalExceptionHandler
捕获,并处理。代码如下
package com.dasheng.controller; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONObject; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.dasheng.util.HLogger; /** * @author dashegn * 欢迎 控制器 */ @RestController public class WelcomeController { /** * 输出欢迎信息,hello world! * 2015年9月26日 下午2:58:58 * dasheng * @return */ @RequestMapping(value = "helloWorld", produces = {"text/html;charset=utf-8"} ) public String sayHelloWorld() { HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder .getRequestAttributes()).getRequest(); String requestURL = request.getRequestURI(); HLogger.info(requestURL); String hi = "hello world! My name is Dasheng..."; return hi; } @RequestMapping(value = "exception", produces = {"text/html;charset=utf-8"} ) public String handleException() { HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder .getRequestAttributes()).getRequest(); String requestURL = request.getRequestURI(); HLogger.info(requestURL); String hi = "{"id":1,"name":"dasheng"}"; JSONObject hiJson = JSONObject.fromObject(hi); String id = hiJson.getString("id"); String exception = hiJson.getString("age"); //此处抛出异常 return hi; } }
Spring功能强大,逐步探索吧。