Я пишу собственное исключение, где, если имя пользователя уже существует, ответом будет пользовательское исключение, т. е. UserException в json.
UsernameAlreadyExistException.java сильный>
package com.crawler.exception;
public class UsernameAlreadyExistException extends RuntimeException {
public UsernameAlreadyExistException(String message) {
super(message);
}
public UsernameAlreadyExistException(String message, Throwable cause) {
super(message, cause);
}
}
UserException.java
package com.crawler.exception;
import org.springframework.http.HttpStatus;
public class UserException {
private final String message;
private final Throwable throwable;
private final HttpStatus httpStatus;
public UserException(String message, Throwable throwable, HttpStatus httpStatus) {
this.message = message;
this.throwable = throwable;
this.httpStatus = httpStatus;
}
public String getMessage() {
return message;
}
public Throwable getThrowable() {
return throwable;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
}
UserExceptionHandler
package com.crawler.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class UserExceptionHandler {
@ExceptionHandler(value = {UsernameAlreadyExistException.class})
public ResponseEntity handleUsernameAlreadyExistException(UsernameAlreadyExistException usernameAlreadyExistException) {
UserException userException = new UserException(
usernameAlreadyExistException.getMessage(),
usernameAlreadyExistException.getCause(),
HttpStatus.CONFLICT
);
return new ResponseEntity(userException, HttpStatus.CONFLICT);
}
}
В реализации службы я написал код, вызывающий исключение UsernameAlreadyExistException.
UserServiceImplementation.java
@Override
public String createUser(User user) {
if (userRepository.findByUsername(user.getUsername()) != null) {
throw new UsernameAlreadyExistException("Username already exist.");
}
userRepository.save(user);
return "User created successfully.";
}
Это вывод консоли.
2024-09-24T13:41:43.809Z ERROR 1 --- [backend] [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: com.crawler.exception.UsernameAlreadyExistException: Username already exist.] with root cause
Ответ от POSTMAN.
{
"timestamp": "2024-09-24T13:41:43.878+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/v1/users"
}
Ожидается ответ от POSTMAN.
{
"message": "Username already exist",
"throwable": null,
"httpStatus": "CONFLICT"
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... er-error-i
Ожидание пользовательского исключения в ответе json вместо внутренней ошибки сервера при весенней загрузке ⇐ JAVA
Программисты JAVA общаются здесь
1727193240
Anonymous
Я пишу собственное исключение, где, если имя пользователя уже существует, ответом будет пользовательское исключение, т. е. UserException в json.
[b]UsernameAlreadyExistException.java сильный>
package com.crawler.exception;
public class UsernameAlreadyExistException extends RuntimeException {
public UsernameAlreadyExistException(String message) {
super(message);
}
public UsernameAlreadyExistException(String message, Throwable cause) {
super(message, cause);
}
}
UserException.java[/b]
package com.crawler.exception;
import org.springframework.http.HttpStatus;
public class UserException {
private final String message;
private final Throwable throwable;
private final HttpStatus httpStatus;
public UserException(String message, Throwable throwable, HttpStatus httpStatus) {
this.message = message;
this.throwable = throwable;
this.httpStatus = httpStatus;
}
public String getMessage() {
return message;
}
public Throwable getThrowable() {
return throwable;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
}
[b]UserExceptionHandler[/b]
package com.crawler.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class UserExceptionHandler {
@ExceptionHandler(value = {UsernameAlreadyExistException.class})
public ResponseEntity handleUsernameAlreadyExistException(UsernameAlreadyExistException usernameAlreadyExistException) {
UserException userException = new UserException(
usernameAlreadyExistException.getMessage(),
usernameAlreadyExistException.getCause(),
HttpStatus.CONFLICT
);
return new ResponseEntity(userException, HttpStatus.CONFLICT);
}
}
В реализации службы я написал код, вызывающий исключение UsernameAlreadyExistException.
[b]UserServiceImplementation.java[/b]
@Override
public String createUser(User user) {
if (userRepository.findByUsername(user.getUsername()) != null) {
throw new UsernameAlreadyExistException("Username already exist.");
}
userRepository.save(user);
return "User created successfully.";
}
Это вывод консоли.
2024-09-24T13:41:43.809Z ERROR 1 --- [backend] [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: com.crawler.exception.UsernameAlreadyExistException: Username already exist.] with root cause
Ответ от POSTMAN.
{
"timestamp": "2024-09-24T13:41:43.878+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/v1/users"
}
Ожидается ответ от POSTMAN.
{
"message": "Username already exist",
"throwable": null,
"httpStatus": "CONFLICT"
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79018948/expecting-a-custom-exception-in-json-response-instead-an-internal-server-error-i[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия