powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Обработка исключений @ControllerAdvice
2 сообщений из 2, страница 1 из 1
Обработка исключений @ControllerAdvice
    #39176335
JulT
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Spring MVC, настраиваю глобальный перехват исключений:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
@ControllerAdvice
public class GlobalExceptionHandler
....
@ResponseBody
    @ExceptionHandler(UserNotFound.class)
    public ExceptionJSONInfo userNotFound(UserNotFound userNotFound, HttpServletRequest request){
        return new ExceptionJSONInfo(userNotFound.getMessage(), request.getRequestURL().toString());
    }


UserNotFound такой:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
@ResponseStatus(value = HttpStatus.OK)
public class UserNotFound extends RuntimeException {
    public UserNotFound(){
    }
    public UserNotFound(String message){
        super(message);
    }
}


Класс ошибки, который должен "обернуться" в json и улететь пользователю:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
public class ExceptionJSONInfo {
    private String message;
    private String url;

    public ExceptionJSONInfo(){
    }
...
get/set



Метод контроллера:
Код: java
1.
2.
3.
4.
5.
6.
7.
@RequestMapping(value = "/login", method = RequestMethod.POST) 
    @ResponseBody LoginResponse login(@RequestBody LoginRequest request){
        LoginResponse response = new LoginResponse();
        String token = clientService.login(request.getLoginUserInfo());
        response.setToken(token);
        return response;
    }


В слое сервиса, если пользователь не найден, генерируется ошибка:
Код: java
1.
2.
3.
if(client == null) {
            throw new UserNotFound("user not found");
        }


LoginResponse выглядит следующим образом:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
public class LoginResponse {
    private String token;
    public String getToken() {
        return token;
    }
    public void setToken(String token) {
        this.token = token;
    }
}


Когда возникает ошибка(throw new UserNotFound), ожидаю, что ответ придет пользователю в виде json:
Код: java
1.
{"message":"user not found","url":"http://localhost:8080/client/login"}


Но не тут то было, вылетает ошибка:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized field "message" (class ru.halt.practice.rest.LoginResponse), not marked as ignorable (one known property: "token"])
 at [Source: java.io.PushbackInputStream@19b62af; line: 1, column: 13] (through reference chain: ru.halt.practice.rest.LoginResponse["message"]); nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "message" (class ru.halt.practice.rest.LoginResponse), not marked as ignorable (one known property: "token"])
 at [Source: java.io.PushbackInputStream@19b62af; line: 1, column: 13] (through reference chain: ru.halt.practice.rest.LoginResponse["message"])
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:224)
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:208)
	at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:95)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:599)
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
	at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:357)
	at ClientControllerTest.testLogin(ClientControllerTest.java:68)


И это все при том, что в WebConfig:
Код: java
1.
2.
3.
4.
@EnableWebMvc 
@Configuration
@ComponentScan({"ru.halt.practice.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {


прописан конвертер:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        converters.add(new StringHttpMessageConverter());
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
        super.configureMessageConverters(converters);
    }


когда ошибки нет(пользователь найден), json возвращается без проблем.
До GlobalExceptionHandler и метода public ExceptionJSONInfo userNotFound ошибка долетает, но конвертится в json не хочет.
Не могу понять что поломалось. Помогите плиз
...
Рейтинг: 0 / 0
Обработка исключений @ControllerAdvice
    #39176774
JulT
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Проблема была в версии библиотеки jackson, так и голову сломать можно....
Есть метод контроллера, в нем руками генерирую ошибку:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
@RequestMapping(value = "/id", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    ClientInfo client(@RequestBody(required = false) PageSearch filter){
        if(true){
            throw new UserNotFound("User Not FOUND");
        }
        Client client = clientService.getById(filter.getId());
        ClientInfo clientInfo = ModelUtil.toModel(client);
        return clientInfo;
    }


В браузере перехожу по адресу: http://localhost:8080/client/id, в результате чего срабатывает метод из контроллера @ControllerAdvice:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
@ExceptionHandler(UserNotFound.class)
    public @ResponseBody ExceptionJSONInfo userNotFound(UserNotFound userNotFound){
        System.out.println("userNotFound =========== " + userNotFound);
        ExceptionJSONInfo jsonUserNotFound = new ExceptionJSONInfo(); // BUNDLE.getString("userNotFound")
        jsonUserNotFound.setMessage(userNotFound.getMessage());
        jsonUserNotFound.setUrl("urllll");
        return jsonUserNotFound;
    }


И на страничке появляется json: {"message":"User Not FOUND","url":"urllll"}
Все прекрасно. Но! Когда делаю через тестовый метод:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
@Test
    public void testGetById() throws Exception{
        PageSearch request = new PageSearch();
        request.setId(5L);
        String asString = OBJECT_MAPPER.writeValueAsString(request);
        ClientInfo client = TEMPLATE.postForObject("http://localhost:8080/client/id", request, ClientInfo.class);
        client.getLogin();
        client.getPassword();
    }


где:
Код: java
1.
2.
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private static final RestTemplate TEMPLATE = Utils.template();


и:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
public class Utils {
    public static RestTemplate template() {
        RestTemplate template = new RestTemplate();
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJackson2HttpMessageConverter());
        converters.add(new StringHttpMessageConverter());
        template.setMessageConverters(converters);
        template.setRequestFactory(new SimpleClientHttpRequestFactory());
        return template;
    }
}


Получаю - см. вложение.
Почему возвращается client, а не {"message":"Not FOUND user","url":"urllll"}????
И второй вопрос, почему при throw new UserNotFound("User Not FOUND"); в консоль перестал выводиться стектрейс ошибки.
Мой log4j.properties:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
log4j.rootLogger=DEBUG,Stdout
log4j.appender.Stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

log4j.logger.org.hibernate=INFO
log4j.logger.org.springframework=INFO
org.springframework.security.level=DEBUG
log4j.category.ru.halt.practice=STDOUT


Очень прошу помощи
...
Рейтинг: 0 / 0
2 сообщений из 2, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Обработка исключений @ControllerAdvice
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]