注意:SpringBoot(SpringMVC)里的Handler特指@Controller注解的类里的每个处理HTTP请求的一个public method.
并且要注意这里spring-boot版本是1.5.0.RELEASE. 另外需要添加spring-boot-maven-plugin实例参考spring-boot-demo项目,它的pom如下:
packageorg.flylib.boot.starter.handler;importorg.flylib.boot.starter.exception.CustomRuntimeException;importorg.flylib.boot.starter.exception.UnknownResourceException;importorg.flylib.boot.starter.exception.ValidationRuntimeException;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.TypeMismatchException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.MessageSource;importorg.springframework.core.env.Environment;importorg.springframework.http.HttpStatus;importorg.springframework.http.converter.HttpMessageNotReadableException;importorg.springframework.ui.Model;importorg.springframework.web.HttpMediaTypeNotAcceptableException;importorg.springframework.web.HttpMediaTypeNotSupportedException;importorg.springframework.web.HttpRequestMethodNotSupportedException;importorg.springframework.web.bind.MissingServletRequestParameterException;importorg.springframework.web.bind.annotation.ControllerAdvice;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.ResponseBody;importorg.springframework.web.context.request.ServletWebRequest;importorg.springframework.web.servlet.LocaleResolver;importorg.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.util.HashMap;importjava.util.LinkedHashMap;importjava.util.Locale;importjava.util.Map;/** * 说明: * * @ControllerAdvice是controller的一个辅助类,最常用的就是作为全局异常处理的切面类 * @ControllerAdvice可以指定扫描范围 * @ControllerAdvice约定了几种可行的返回值,如果是直接返回model类的话,需要使用@ResponseBody进行json转换 返回String,表示跳到某个view * 返回modelAndView * 返回model + @ResponseBody * 全局异常处理 */@ControllerAdvicepublicclassGlobalExceptionHandler {privatestaticfinalLoggerlog =LoggerFactory.getLogger(GlobalExceptionHandler.class);@AutowiredprivateEnvironmentenv;@Autowired(required =false)privateMessageSourcemessageSource;@Autowired(required =false)privateLocaleResolverlocaleResolver;privatestaticfinalStringdefaultMoreInfoUrl ="";privatefinalMap<String,HttpStatus>DEFAULT_EXCEPTION_MAPPING_DEFINITIONS;publicGlobalExceptionHandler() {DEFAULT_EXCEPTION_MAPPING_DEFINITIONS =createDefaultExceptionMappingDefinitions(); }@ExceptionHandler//处理所有异常@ResponseBody//在返回自定义相应类的情况下必须有,这是@ControllerAdvice注解的规定publicMap<String,Object>exceptionHandler(Throwablee,HttpServletRequestrequest,HttpServletResponseresponse,Modelmodel) {//log.error("handle error:",e);HttpStatushttpStatus =DEFAULT_EXCEPTION_MAPPING_DEFINITIONS.get(e.getClass().getName());if(httpStatus==null){httpStatus =HttpStatus.INTERNAL_SERVER_ERROR; }//是否是生产环境booleanisProd ="prod".equals(env.getActiveProfiles()[0]);Map<String,Object>map =newHashMap<String,Object>();if(e.getCause()instanceofCustomRuntimeException){CustomRuntimeExceptionexception = (CustomRuntimeException)e.getCause();map.put("code",String.valueOf(exception.getCode()));map.put("message",exception.getMessage()); }elseif(e.getCause()instanceofValidationRuntimeException){ValidationRuntimeExceptionexception = (ValidationRuntimeException)e.getCause();map.put("code",String.valueOf(exception.getCode()));map.put("message",exception.getMessage());httpStatus =HttpStatus.BAD_REQUEST; }else {map.put("code",String.valueOf(httpStatus.value()));map.put("message",httpStatus.toString()); }//不是生产环境,添加调试信息if(!isProd){map.put("throwable",e); }response.setStatus(httpStatus.value());returnmap; }protectedfinalMap<String,HttpStatus>createDefaultExceptionMappingDefinitions() {Map<String,HttpStatus>m =newLinkedHashMap<String,HttpStatus>();// 400applyDef(m,HttpMessageNotReadableException.class,HttpStatus.BAD_REQUEST);applyDef(m,MissingServletRequestParameterException.class,HttpStatus.BAD_REQUEST);applyDef(m,TypeMismatchException.class,HttpStatus.BAD_REQUEST);applyDef(m,"javax.validation.ValidationException",HttpStatus.BAD_REQUEST);// 404applyDef(m,NoSuchRequestHandlingMethodException.class,HttpStatus.NOT_FOUND);applyDef(m,"org.hibernate.ObjectNotFoundException",HttpStatus.NOT_FOUND);// 405applyDef(m,HttpRequestMethodNotSupportedException.class,HttpStatus.METHOD_NOT_ALLOWED);// 406applyDef(m,HttpMediaTypeNotAcceptableException.class,HttpStatus.NOT_ACCEPTABLE);// 409//can't use the class directly here as it may not be an available dependency:applyDef(m,"org.springframework.dao.DataIntegrityViolationException",HttpStatus.CONFLICT);// 415applyDef(m,HttpMediaTypeNotSupportedException.class,HttpStatus.UNSUPPORTED_MEDIA_TYPE);applyDef(m,UnknownResourceException.class,HttpStatus.NOT_FOUND);returnm; }privatevoidapplyDef(Map<String,HttpStatus>m,Classclazz,HttpStatusstatus) {applyDef(m,clazz.getName(),status); }privatevoidapplyDef(Map<String,HttpStatus>m,Stringkey,HttpStatusstatus) {m.put(key,status); }protectedStringgetMessage(Stringmsg,ServletWebRequestwebRequest,Exceptionex) {if (msg !=null) {if (msg.equalsIgnoreCase("null") ||msg.equalsIgnoreCase("off")) {returnnull; }msg =ex.getMessage();if (messageSource !=null) {Localelocale =null;if (localeResolver !=null) {locale =localeResolver.resolveLocale(webRequest.getRequest()); }msg =messageSource.getMessage(msg,null,msg,locale); } }returnmsg; }}