码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC 类型转换错误自定义返回

时间:2015-04-25 16:42:01      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:springmvc

在SpringMVC捕获异常只需要实现接口org.springframework.web.servlet.HandlerExceptionResolver,即可自定义返回异常,如:属性转换异常

    @RequestMapping("/test")
	@ResponseBody
	public String str(Integer age) throws Exception {
		return "test:" + age;
	}

如果调用方法时传入参数age=abc此时会抛出TypeMismatchException,在自定义的异常捕获中,只需要根据信息进行返回:

package com.cml.mvc.exception;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.cml.mvc.beans.Result;
import com.google.gson.Gson;

public class MyExceptionHandler implements HandlerExceptionResolver {

	private static Log log = LogFactory.getLog(MyExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		log.info("异常捕获=======>" + ex);
		log.info("异常捕获=======>" + handler);

		Result result = new Result();

		// 返回错误信息不为空
		if (ex instanceof TypeMismatchException && null != ex.getMessage()) {
			result.setResult(ex.getMessage());
		} else {
			result.setResult("500 服务器异常!");
		}

		response.setHeader("content-type", "application/json");
		response.setCharacterEncoding("UTF-8");
		try {
			Writer writer = response.getWriter();
			writer.write(new Gson().toJson(result));
			writer.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return null;
	}

}

这样,属性类型转换错误被自定义返回了,但是也有个缺点,在一个方法总如果有多个参数,但是传入时有多个参数类型错误,只能捕获到第一个属性转换异常信息

设想:如果可以获取到所有类型转换错误信息,那是多perfect啊,研究中。。。。


SpringMVC 类型转换错误自定义返回

标签:springmvc

原文地址:http://blog.csdn.net/cml_blog/article/details/45271261

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!