springmvc中自定义异常处理器输出异常信息

 
  
 
  

1.可以使用springmvc提供的HandlerExceptionResolver,来实现统一的异常处理。

package com.catchu.utils;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 异常处理器
 * @author 刘俊重
 * @email [email protected]
 */
@Component
public class MagicExceptionHandler implements HandlerExceptionResolver {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		WebResult result = new WebResult();
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			
			if (ex instanceof CatchUException) {
				result.put("code", ((MagicException) ex).getCode());
				result.put("msg", ((MagicException) ex).getMessage());
			}else{
				result = Out.error();
			}
			
			//记录异常日志
			logger.error(ex.getMessage(), ex);
			
			String json = JSON.toJSONString(result);
			response.getWriter().print(json);
		} catch (Exception e) {
			logger.error("CatchUExceptionHandler 异常处理失败", e);
		}
		return new ModelAndView();
	}
}

2.MagicException异常类定义如下:

package com.magic.lang;
/**
 * @author 刘俊重
 * @Description 自定义异常
 */
public class MagicException extends RuntimeException {

    private String msg;

    private int code;

    public MagicException(String msg){
        super(msg);
        this.msg = msg;
    }

    public MagicException(String msg,Throwable e){
        super(msg,e);
        this.msg = msg;
    }

    public MagicException(String msg,int code){
        super(msg);
        this.msg = msg;
        this.code = code;
    }

    public MagicException(String msg,int code,Throwable e){
        super(msg,e);
        this.msg = msg;
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}


 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
  

你可能感兴趣的:(工具类)