Skip to content

Commit 55d4a0f

Browse files
authored
readme
readme
1 parent 4499305 commit 55d4a0f

File tree

1 file changed

+164
-1
lines changed

1 file changed

+164
-1
lines changed

README.md

Lines changed: 164 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ flylib-boot是针对springboot构建的程序的基础框架,专门用于构
33
异常处理
44

55
## 功能
6-
1. 统一的异常处理
6+
1. 全局的异常处理
77
2. 其它
88

99
## 使用方法
@@ -88,3 +88,166 @@ flylib-boot是针对springboot构建的程序的基础框架,专门用于构
8888
throwable:{...}
8989
}
9090
```
91+
实现代码是
92+
```
93+
package org.flylib.boot.starter.handler;
94+
95+
import org.flylib.boot.starter.exception.CustomRuntimeException;
96+
import org.flylib.boot.starter.exception.UnknownResourceException;
97+
import org.flylib.boot.starter.exception.ValidationRuntimeException;
98+
import org.slf4j.Logger;
99+
import org.slf4j.LoggerFactory;
100+
import org.springframework.beans.TypeMismatchException;
101+
import org.springframework.beans.factory.annotation.Autowired;
102+
import org.springframework.context.MessageSource;
103+
import org.springframework.core.env.Environment;
104+
import org.springframework.http.HttpStatus;
105+
import org.springframework.http.converter.HttpMessageNotReadableException;
106+
import org.springframework.ui.Model;
107+
import org.springframework.web.HttpMediaTypeNotAcceptableException;
108+
import org.springframework.web.HttpMediaTypeNotSupportedException;
109+
import org.springframework.web.HttpRequestMethodNotSupportedException;
110+
import org.springframework.web.bind.MissingServletRequestParameterException;
111+
import org.springframework.web.bind.annotation.ControllerAdvice;
112+
import org.springframework.web.bind.annotation.ExceptionHandler;
113+
import org.springframework.web.bind.annotation.ResponseBody;
114+
import org.springframework.web.context.request.ServletWebRequest;
115+
import org.springframework.web.servlet.LocaleResolver;
116+
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
117+
118+
import javax.servlet.http.HttpServletRequest;
119+
import javax.servlet.http.HttpServletResponse;
120+
import java.util.HashMap;
121+
import java.util.LinkedHashMap;
122+
import java.util.Locale;
123+
import java.util.Map;
124+
125+
/**
126+
* 说明:
127+
*
128+
* @ControllerAdvice是controller的一个辅助类,最常用的就是作为全局异常处理的切面类
129+
* @ControllerAdvice可以指定扫描范围
130+
* @ControllerAdvice约定了几种可行的返回值,如果是直接返回model类的话,需要使用@ResponseBody进行json转换 返回String,表示跳到某个view
131+
* 返回modelAndView
132+
* 返回model + @ResponseBody
133+
* 全局异常处理
134+
*/
135+
@ControllerAdvice
136+
public class GlobalExceptionHandler {
137+
138+
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
139+
140+
@Autowired
141+
private Environment env;
142+
143+
@Autowired(required = false)
144+
private MessageSource messageSource;
145+
146+
@Autowired(required = false)
147+
private LocaleResolver localeResolver;
148+
149+
private static final String defaultMoreInfoUrl = "";
150+
151+
private final Map<String,HttpStatus> DEFAULT_EXCEPTION_MAPPING_DEFINITIONS;
152+
153+
public GlobalExceptionHandler() {
154+
DEFAULT_EXCEPTION_MAPPING_DEFINITIONS = createDefaultExceptionMappingDefinitions();
155+
}
156+
157+
@ExceptionHandler//处理所有异常
158+
@ResponseBody //在返回自定义相应类的情况下必须有,这是@ControllerAdvice注解的规定
159+
public Map<String,Object> exceptionHandler(Throwable e, HttpServletRequest request, HttpServletResponse response, Model model) {
160+
//
161+
log.error("handle error:",e);
162+
163+
HttpStatus httpStatus = DEFAULT_EXCEPTION_MAPPING_DEFINITIONS.get(e.getClass().getName());
164+
if(httpStatus==null){
165+
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
166+
}
167+
//是否是生产环境
168+
boolean isProd = "prod".equals(env.getActiveProfiles()[0]);
169+
Map<String,Object> map = new HashMap<String,Object>();
170+
if(e.getCause() instanceof CustomRuntimeException){
171+
CustomRuntimeException exception = (CustomRuntimeException) e.getCause();
172+
map.put("code",String.valueOf(exception.getCode()));
173+
map.put("message",exception.getMessage());
174+
}else if(e.getCause() instanceof ValidationRuntimeException){
175+
ValidationRuntimeException exception = (ValidationRuntimeException) e.getCause();
176+
map.put("code",String.valueOf(exception.getCode()));
177+
map.put("message",exception.getMessage());
178+
httpStatus = HttpStatus.BAD_REQUEST;
179+
}else {
180+
map.put("code",String.valueOf(httpStatus.value()));
181+
map.put("message",httpStatus.toString());
182+
}
183+
184+
185+
//不是生产环境,添加调试信息
186+
if(!isProd){
187+
map.put("throwable",e);
188+
}
189+
response.setStatus(httpStatus.value());
190+
return map;
191+
}
192+
193+
protected final Map<String,HttpStatus> createDefaultExceptionMappingDefinitions() {
194+
195+
Map<String,HttpStatus> m = new LinkedHashMap<String, HttpStatus>();
196+
197+
// 400
198+
applyDef(m, HttpMessageNotReadableException.class, HttpStatus.BAD_REQUEST);
199+
applyDef(m, MissingServletRequestParameterException.class, HttpStatus.BAD_REQUEST);
200+
applyDef(m, TypeMismatchException.class, HttpStatus.BAD_REQUEST);
201+
applyDef(m, "javax.validation.ValidationException", HttpStatus.BAD_REQUEST);
202+
203+
// 404
204+
applyDef(m, NoSuchRequestHandlingMethodException.class, HttpStatus.NOT_FOUND);
205+
applyDef(m, "org.hibernate.ObjectNotFoundException", HttpStatus.NOT_FOUND);
206+
207+
// 405
208+
applyDef(m, HttpRequestMethodNotSupportedException.class, HttpStatus.METHOD_NOT_ALLOWED);
209+
210+
// 406
211+
applyDef(m, HttpMediaTypeNotAcceptableException.class, HttpStatus.NOT_ACCEPTABLE);
212+
213+
// 409
214+
//can't use the class directly here as it may not be an available dependency:
215+
applyDef(m, "org.springframework.dao.DataIntegrityViolationException", HttpStatus.CONFLICT);
216+
217+
// 415
218+
applyDef(m, HttpMediaTypeNotSupportedException.class, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
219+
applyDef(m, UnknownResourceException.class, HttpStatus.NOT_FOUND);
220+
221+
return m;
222+
}
223+
private void applyDef(Map<String,HttpStatus> m, Class clazz, HttpStatus status) {
224+
applyDef(m, clazz.getName(), status);
225+
}
226+
227+
private void applyDef(Map<String,HttpStatus> m, String key, HttpStatus status) {
228+
m.put(key, status);
229+
}
230+
231+
232+
233+
protected String getMessage(String msg, ServletWebRequest webRequest, Exception ex) {
234+
235+
if (msg != null) {
236+
if (msg.equalsIgnoreCase("null") || msg.equalsIgnoreCase("off")) {
237+
return null;
238+
}
239+
msg = ex.getMessage();
240+
if (messageSource != null) {
241+
Locale locale = null;
242+
if (localeResolver != null) {
243+
locale = localeResolver.resolveLocale(webRequest.getRequest());
244+
}
245+
msg = messageSource.getMessage(msg, null, msg, locale);
246+
}
247+
}
248+
249+
return msg;
250+
}
251+
}
252+
253+
```

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy