Я разрабатываю приложение RESTful, используя Spring. Я хочу обработать случай, когда в теле запроса POST имеет неправильный тип данных - PullRequest
0 голосов
/ 08 мая 2019

Я использую веб-сервисы создания весенней загрузки, и один из них получает объект от:

public class GroupRouteRequestDTO {
    private Long groupID;
    private String userToken;
    private Long pageIndex; 

    private Long pageSize;
    private String search;
    }

класс

в почтальоне делаю запрос с телом

{
    "groupID":"11AA",
    "userToken": "9a",
    "pageIndex":0,
    "pageSize":12,
    "search":"A"

}

Я получаю

{
    "timestamp": 1557340656686,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
    "message": "Could not read document: Can not deserialize value of type java.lang.Long from String \"11AA\": not a valid Long value\n at [Source: java.io.PushbackInputStream@1226796e; line: 2, column: 12] (through reference chain: com.ntgclarity.ngnts.datatransferobject.GroupRouteRequestDTO[\"groupID\"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.lang.Long from String \"11AA\": not a valid Long value\n at [Source: java.io.PushbackInputStream@1226796e; line: 2, column: 12] (through reference chain: com.ntgclarity.ngnts.datatransferobject.GroupRouteRequestDTO[\"groupID\"])",
    "path": "/toDoList/Employee"
} 

этот ответ от почтальона

А веб-сервис

@PostMapping
    @RequestMapping("/Employee")
    @ResponseStatus(HttpStatus.CREATED)
    @PreAuthorize("hasAuthority('ToDoList_Access')")
    public Object getEmployeesRoutList(@Valid @RequestBody GroupRouteRequestDTO groupRouteRequest,HttpServletRequest request)
            throws EntityNotFoundException {
        return toDoListService.getEmployeesRoutList(groupRouteRequest,request);
    } 

Вопрос: можно ли настроить сообщение об ошибке из веб-службы для обработки, когда тело запроса имеет неправильный тип данных?

Ответы [ 2 ]

0 голосов
/ 16 мая 2019

Я решаю проблему, добавив этот метод в класс контроллера

    @ResponseBody
    public ResponseEntity<Object> MessageNotReadableException(HttpMessageNotReadableException ex,HttpServletResponse response){
        ex.printStackTrace();
        return new ResponseEntity<Object>("Bad Request Please Check Your Inputs",HttpStatus.BAD_REQUEST);
    }```

0 голосов
/ 08 мая 2019

Вы можете использовать Bean Validation. Ссылка ссылка

Например:

import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.constraints.Email;

    public class User {

        @NotNull(message = "Name cannot be null")
        private String name;

        @AssertTrue
        private boolean working;

        @Size(min = 10, max = 200, message 
          = "About Me must be between 10 and 200 characters")
        private String aboutMe;

        @Min(value = 18, message = "Age should not be less than 18")
        @Max(value = 150, message = "Age should not be greater than 150")
        private int age;

        @Email(message = "Email should be valid")
        private String email;

        // standard setters and getters 
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...