com.github.jackpanz.spring.exception.MExceptionHandler Maven / Gradle / Ivy
The newest version!
package com.github.jackpanz.spring.exception;
import com.alibaba.fastjson.JSONObject;
import com.github.jackpanz.spring.util.ResultMap;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import java.lang.reflect.Method;
/**
* Created by bj on 2017/6/20.
*/
public class MExceptionHandler extends ExceptionHandlerExceptionResolver {
public ModelAndView doResolveHandlerMethodException(HttpServletRequest request,
HttpServletResponse response,
HandlerMethod handlerMethod,
Exception ex) {
ex.printStackTrace();
if (handlerMethod == null) {
return new ModelAndView("error");
}
Method method = handlerMethod.getMethod();
if (method == null) {
return new ModelAndView("error");
}
ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(method, ResponseBody.class);
if (responseBodyAnn != null) {
response.setStatus(HttpStatus.OK.value()); //设置状态码
response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
response.setCharacterEncoding("UTF-8"); //避免乱码
response.setHeader("Cache-Control", "no-cache, must-revalidate");
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("action",false);
if( ex == null || StringUtils.isBlank(ex.getMessage()) ){
jsonObject.put("msg", ResultMap.DEFAULT_FAIL_MSG);
} else {
jsonObject.put("msg", ex.getMessage());
}
response.getWriter().write(jsonObject.toJSONString());
}catch (Exception x){
ex.printStackTrace();
}
return new ModelAndView();
}
return new ModelAndView("error");
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy