2015-03-27 12 views
6

Spring Boot uygulamasında tek bir yöntemle bir RestController var. Bu yöntem, POST isteklerini/foo url'ye işler. Parametre olarak bir ID ve bir DTO nesnesi alır. DTO nesnesi, Jackson tarafından serileştiriliyor. Geçirilen çift özelliklerini doğrulamak için DTO parametresine @Valid ekledim. Sorunum, int olması gereken bir alan için bir String’i geçtiğimde yatar. Bu bir HttpMessageNotReadableException tetikler ve çıktı "iletisi" sınıf ve paket adları gibi iç nesne gösterimi bilgileri içerir. Bu hata, bir noktada @Valid için hazırda bekletme onaylamadan önce Jackson serileştirme mantığında gerçekleşiyor. Denetleyicimde, bu tür istisnaları işleyen bir @ExceptionHandler açıklamalı yöntem oluşturabilirim, ancak json çıktısını el ile yapmam ya da Spring'in Jackson'dan kullandığı varsayılan iletiyle yapışmam gerekir.Spring MVC Dinlenme hizmeti için bir Jackson serileştirme hatası olduğunda "iletiyi" hatayı nasıl özelleştirebilirim?

Bu, bu durum oluştuğunda Bahar çıkışı budur:

{ 
"timestamp": 1427473174263, 
"status": 400, 
"error": "Bad Request", 
"exception": "org.springframework.http.converter.HttpMessageNotReadableException", 
"message": "Could not read JSON: Can not construct instance of int from String value 'SHOULDNT BE A STRING': not a valid Integer value\ at [Source: [email protected]; line: 1, column: 3] (through reference chain: com.blah.foo.dto.CustomerProductPromotionDTO[\"productId\"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of int from String value 'SHOULDNT BE A STRING': not a valid Integer value\ at [Source: [email protected]; line: 1, column: 3] (through reference chain: com.blah.foo.dto.CustomerProductPromotionDTO[\"productId\"])", 
"path": "/customers/123456/promotions" 
} 

Bunu nasıl "mesaj" alanına kişiselleştirebilirim?

cevap

3

Bu Jackson hatasıyla uğraşmanın ve hala Spring'in varsayılan geri kalan yanıtlarını kullanmanın en iyi yolunun ne olduğunu düşündüğümü düşündüm. Bu özel olmayan özel durum türleri için @ExceptionHandler'ı @ResponseStatus ile birlikte kullanabileceğinizi anlayamadım.

*/ 
@ExceptionHandler(HttpMessageNotReadableException.class) 
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="There was an error processing the request body.") 
public void handleMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException exception) { 
    LOGGER.error("\nUnable to bind post data sent to: " + request.getRequestURI() + "\nCaught Exception:\n" + exception.getMessage()); 
}