2013-04-03 27 views
3

我休息web服務期望一個數:彈簧,示出了用於無效參數的寧靜web服務的自定義錯誤消息(使用從彈簧自動參數轉換)

@RequestMapping(value = "/bb/{number}", method = RequestMethod.GET, produces = "plain/text") 
public void test(@PathVariable final double number, final HttpServletResponse response) 

然而,如果客戶端通過一而不是一些文本,「QQQ」, 客戶從春天獲得類似這樣的錯誤:

HTTP Status 500 - 
The server encountered an internal error() that prevented it from fulfilling this request. 
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'double'; nested exception is java.lang.NumberFormatException: For input string: "QQQ" 
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894) 
... 

我需要處理這種情況,並顯示相應的錯誤信息,如:

<MyError> 
    <InvalidParameter parameterName="number"/> 
    <message>...</message> 
</MyError> 

我怎麼能這樣做?

這可以通過捕獲org.springframework.beans.TypeMismatchException異常(如以下代碼所示), 來實現,但它有許多問題。例如,可能有其他TypeMismatchException異常與解析和轉換Web服務請求的參數無關。

import org.springframework.beans.TypeMismatchException; 
import javax.annotation.*; 
import javax.servlet.http.*; 
import org.springframework.http.HttpStatus; 
import org.springframework.stereotype.Controller; 
import org.springframework.context.annotation.Scope; 
import org.springframework.web.bind.annotation.*; 

@Controller 
@RequestMapping(value = "/aa") 
public class BaseController { 

    @RequestMapping(value = "/bb/{number}", method = RequestMethod.GET, produces = "plain/text") 
    public void test(@PathVariable final double number, final HttpServletResponse response) throws IOException { 
     throw new MyException("whatever"); 
    } 

    @ResponseBody 
    @ExceptionHandler 
    public MyError handleException(final Exception exception) throws IOException { 
     if (exception instanceof TypeMismatchException) { 
      response.setStatus(HttpStatus.BAD_REQUEST.value()); 
      TypeMismatchException e = (TypeMismatchException) exception; 
      String msg = "the value for parameter " + e.getPropertyName() + " is invalid: " + e.getValue(); 
      return new MyError(msg); 
     } 

     response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); 
     return MyError("Unknown internal error"); 
    } 
} 

那麼,如何顯示自定義錯誤消息,如果客戶有一個無效的號碼來電,如http://example.com/aa/bb/QQQ

PS:一個解決方案是定義「數字」參數爲字符串,並從我的函數內部做轉換(當時我能趕上並拋出我的自定義除外)。在這個問題中,我在保持spring的自動參數轉換的同時要求解決方案。

PS:另外,春天來響應一個「HTTP 500內部服務器錯誤」的客戶端,而不是「HTTP 400錯誤的請求」。這有意義嗎?!

+0

不是檢查'的生成自定義消息的instanceof TypeMismatchException',你可以得到嵌套的異常,如果它是'NumberFormatException'處理它,否則讓別的東西處理它。 –

+0

這也是錯誤的編碼(正如我在這裏發佈的解決方法)。例如,可能會有其他NumberFormatException異常與解析和轉換Web服務請求的參數無關。 –

+0

當然這是錯誤的編碼。但是如果你打算擁有一個通用的ExceptionHandler,這是必須的。如果你想用某種方式來處理你的特定異常,就像你說的那樣,有一個你自己分析和轉換的String參數。您預期可以通過其他Web服務提升多少個NFE? –

回答

1

使用BindingResult在你的控制器類。它將使無效字段爲空,現在你可以編寫自己的自定義的驗證類,您可以檢查該申請爲null,則像「有效期需」