SpringMVC异常体系
在服务端经常会遇到需要手动的抛出异常,比如业务系统,校验异常,比较通用的处理方案是在最顶层进行拦截异常,例如Struts的全局异常处理,而Spring的异常处理机制就相对于Struts来说好用多了
首先配置方案如下:
第一种:配置式
<!-- 基于配置文件式的异常处理 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.apache.shiro.authz.UnauthorizedException">error/403</prop>
<prop key="com.sirdc.modules.exceptions.ServiceException">error/503</prop>
</props>
</property>
</bean>
第二种:注解式
<!-- 基于注解式子的异常处理 -->
<bean id="exceptionHandlerExceptionResolver" class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver"></bean>
然后在后端采用@ControllerAdvice注解进行处理
import java.util.List;
import javax.validation.ConstraintViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;
import com.sirdc.modules.exceptions.ServiceException;
import com.sirdc.modules.validator.BeanValidators;
import com.sirdc.modules.web.model.Message;
/**
* 自定义统一异常处理中心
* @author: weihuang.peng
* @version Revision: 0.0.1
* @Date: 2015年1月17日
*/
@ControllerAdvice
public class DefaultExceptionHandler {
/**
* 处理业务异常
* @param request
* @param model
* @param exception
* @return Model
*/
@ExceptionHandler({ServiceException.class})
public ModelAndView processServiceException(NativeWebRequest request, ServiceException exception) {
ModelAndView model = new ModelAndView("/error/503");
model.addObject("exception", exception);
model.addObject("message", "服务器未能处理您的请求");
return model;
}
/**
* 处理校验异常
* @param request
* @param exception
* @return
*/
@ExceptionHandler({ConstraintViolationException.class})
@ResponseBody
public Message processConstraintViolationException(NativeWebRequest request, ConstraintViolationException exception) {
exception.printStackTrace();
List<String> list = BeanValidators.extractPropertyAndMessageAsList(exception, ": ");
list.add(0, "数据验证失败:");
return handleMessage(list.toArray(new String[] {}));
}
@ExceptionHandler({Exception.class})
public ModelAndView processException(NativeWebRequest request, Exception exception) {
exception.printStackTrace();
ModelAndView model = new ModelAndView("/error/500");
model.addObject("exception", exception);
model.addObject("message", "服务器出错了");
return model;
}
/**
* 添加Flash消息
* @param messages 消息
* @return
*/
protected Message handleMessage(String... messages) {
Message model = new Message();
StringBuilder sb = new StringBuilder();
for (String message : messages) {
sb.append(message).append(messages.length > 1 ? "<br/>" : "");
}
model.setCode("500");
model.setMessage(sb.toString());
return model;
}
}