my.suveng.util.handler.SystemExceptionHandler Maven / Gradle / Ivy
package my.suveng.util.handler;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import my.suveng.model.common.Result;
import my.suveng.model.common.interfaces.SpringUtil;
import my.suveng.util.json.Jackson;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@ControllerAdvice
public class SystemExceptionHandler implements SpringUtil {
/**
* 全局异常处理
* @author suwenguang
* @date 2019-09-25
*/
@ExceptionHandler(value = Exception.class)
public void defaultErrorHandler(Exception e, HttpServletResponse response) {
// http 返回结果
if (ObjectUtil.isEmpty(response)) {
return;
}
// 如果已经返回,不处理
if (response.isCommitted()) {
return;
}
//解决乱码, 需要在writer前设置
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("application/json;charset=UTF-8");
// 获取http 的 writer
PrintWriter writer;
try {
writer = response.getWriter();
} catch (IOException ex) {
return;
}
if (ObjectUtil.isEmpty(writer)) {
return;
}
Throwable cause = e.getCause();
String message = e.getMessage();
if (ObjectUtil.isNotEmpty(cause)) {
message = cause.getMessage();
}
writer.write(Jackson.toJsonString(Result.build(HttpStatus.HTTP_INTERNAL_ERROR, message, new Object())));
writer.flush();
writer.close();
}
}