2016-09-29 49 views
17

@RequestParam我有這樣的枚舉:Spring如何與枚舉

public enum SortEnum { 
    asc, desc; 
} 

那我想作爲一個休息的請求的參數使用方法:

@RequestMapping(value = "/events", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 
public List<Event> getEvents(@RequestParam(name = "sort", required = false) SortEnum sort) { 

它正常工作,當我把這些請求

/events 
/events?sort=asc 
/events?sort=desc 

但是當我發送:

/events?sort=somethingElse 

我得到在控制檯500響應這個消息:

2016-09-29 17:20:51.600 DEBUG 5104 --- [ XNIO-2 task-6] com.myApp.aop.logging.LoggingAspect : Enter: com.myApp.web.rest.errors.ExceptionTranslator.processRuntimeException() with argument[s] = [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type [java.lang.String] to required type [com.myApp.common.SortEnum]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam com.myApp.common.SortEnum] for value 'somethingElse'; nested exception is java.lang.IllegalArgumentException: No enum constant com.myApp.common.SortEnum.somethingElse] 
2016-09-29 17:20:51.600 DEBUG 5104 --- [ XNIO-2 task-6] com.myApp.aop.logging.LoggingAspect : Exit: com.myApp.web.rest.errors.ExceptionTranslator.processRuntimeException() with result = <500 Internal Server Error,[email protected],{}> 
2016-09-29 17:20:51.601 WARN 5104 --- [ XNIO-2 task-6] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type [java.lang.String] to required type [com.myApp.common.SortEnum]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam com.myApp.common.SortEnum] for value 'somethingElse'; nested exception is java.lang.IllegalArgumentException: No enum constant com.myApp.common.SortEnum.somethingElse 

有沒有一種方法,以防止從春天拋出這些異常,並設置枚舉爲空?

編輯

的Strelok的接受的答案作品。但是,我決定處理處理MethodArgumentTypeMismatchException。

@ControllerAdvice 
public class ExceptionTranslator { 

    @ExceptionHandler(MethodArgumentTypeMismatchException.class) 
    @ResponseBody 
    public ResponseEntity<Object> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) { 
     Class<?> type = e.getRequiredType(); 
     String message; 
     if(type.isEnum()){ 
      message = "The parameter " + e.getName() + " must have a value among : " + StringUtils.join(type.getEnumConstants(), ", "); 
     } 
     else{ 
      message = "The parameter " + e.getName() + " must be of type " + type.getTypeName(); 
     } 
     return buildResponse(HttpStatus.UNPROCESSABLE_ENTITY, message); 
    } 

回答

18

您可以創建一個自定義轉換器時,提供了無效值將返回null而不是例外。

事情是這樣的:

@Configuration 
public class MyConfig extends WebMvcConfigurationSupport { 
    @Override 
    public FormattingConversionService mvcConversionService() { 
     FormattingConversionService f = super.mvcConversionService(); 
     f.addConverter(new MyCustomEnumConverter()); 
     return f; 
    } 
} 

和一個簡單的轉換器可能是這樣的:

public class MyCustomEnumConverter implements Converter<String, SortEnum> { 
    @Override 
    public SortEnum convert(String source) { 
     try { 
      return SortEnum.valueOf(source); 
     } catch(Exception e) { 
      return null; // or SortEnum.asc 
     } 
    } 
} 
+2

這是th如果您希望全球範圍內針對所有終端都使用此行爲,則爲正確答案如果你只想爲你的一個控制器提供這種行爲,那麼satish chennupati就有正確的解決方案。 – loesak

+0

這樣做後,不知何故,我的oauth2終結點搞砸了,用戶無法驗證 – Olayinka

+0

這是'com.fasterxml.jackson.databind.util.Converter'嗎? –