浏览代码

新增自定义异常处理

周浩 9 年之前
父节点
当前提交
fd6284d694
共有 1 个文件被更改,包括 34 次插入0 次删除
  1. 34 0
      hsweb-web-core/src/main/java/org/hsweb/web/exception/ExceptionHolderConfig.java

+ 34 - 0
hsweb-web-core/src/main/java/org/hsweb/web/exception/ExceptionHolderConfig.java

@@ -0,0 +1,34 @@
+package org.hsweb.web.exception;
+
+import org.hsweb.web.message.ResponseMessage;
+import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.context.request.RequestAttributes;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Created by zhouhao on 16-4-26.
+ */
+@Configuration
+public class ExceptionHolderConfig {
+    @Bean
+    public DefaultErrorAttributes errorAttributes() {
+        return new DefaultErrorAttributes() {
+            @Override
+            public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
+                                                          boolean includeStackTrace) {
+                Integer status = getAttribute(requestAttributes,
+                        "javax.servlet.error.status_code");
+                ResponseMessage responseMessage = new ResponseMessage(false, getError(requestAttributes), status == null ? "" : status.toString());
+                return responseMessage.toMap();
+            }
+
+            public <T> T getAttribute(RequestAttributes requestAttributes, String name) {
+                return (T) requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
+            }
+        };
+    }
+}