Bibi's DevLog ๐ค๐
HTTP Response Body์ ์์ธ error message ์ง์ ํด ๋ณด๋ด๊ธฐ ๋ณธ๋ฌธ
๐ฅ BE ๋ฐฑ์๋
HTTP Response Body์ ์์ธ error message ์ง์ ํด ๋ณด๋ด๊ธฐ
๋น๋น bibi 2021. 4. 30. 19:44Http Response Body์ Exception error message ์ง์ ํ๊ธฐ
์ง์ ๋ง๋ ์๋ฌ๋ฉ์์ง๋ฅผ Http Response์ "message" :
์ ๋ฃ์ด ์ค ์ ์๋ค.
๋จผ์ Exception๊ณผ ์๋ฌ๋ฉ์์ง๋ฅผ ๋ง๋ ๋ค.
DishController.java
// ...
@PutMapping("/{dishId}")
public ResponseEntity<ResponseDto> orderDish(@PathVariable String dishId, @RequestParam("count") int orderSize) {
if (dishService.orderDish(dishId, orderSize)) {
return ResponseEntity.ok().body(new ResponseDto(Status.OK));
}
return ResponseEntity.badRequest().body(new ResponseDto(Status.OUT_OF_STOCK));
}
// ...
DishService.java
@Service
public class DishService {
private CategoryRepository categoryRepository;
public DishService(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
}
public Category findByDishId(String dishId){
return categoryRepository.findByDishId(dishId).orElseThrow(() ->
new NotFoundException(Status.NOTFOUND_DISH.getMessage()));
}
public Dish findDishByDishId(String dishId) {
Category category = findByDishId(dishId);
return category.getDishByDishId(dishId);
}
public boolean orderDish(String dishId, int orderSize) {
Category category = findByDishId(dishId);
Dish dish = findDishByDishId(dishId);
if (dish.checkStock(orderSize)) {
dish.updateStock(orderSize);
category.addDish(dish);
categoryRepository.save(category);
return true;
}
return false;
}
}
NotFoundException.java
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
private String message;
public NotFoundException(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
Status.java
public enum Status {
OK("Success"),
NOTFOUND_CATEGORY("์กด์ฌํ์ง ์๋ ์นดํ
๊ณ ๋ฆฌ์
๋๋ค."),
NOTFOUND_DISH("์กด์ฌํ์ง ์๋ ๋ฐ์ฐฌ์
๋๋ค."),
OUT_OF_STOCK("๋ฐ์ฐฌ ์ฌ๊ณ ๋ถ์กฑ");
private String message;
Status(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
๋ง์ง๋ง์ผ๋ก application.properties
์
server.error.include-message=always
์ ์ถ๊ฐํ๋ค.
์ฐธ๊ณ
https://stackoverflow.com/questions/62561211/spring-responsestatusexception-does-not-return-reason
'๐ฅ BE ๋ฐฑ์๋' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JWT ๊ธฐ์ด] JWT, TOKEN ํ ํฐ ๋ฒ ์ด์ค ๋ก๊ทธ์ธ (0) | 2021.06.04 |
---|---|
[OAuth] ์ํ์ฝ๋ฉ - OAuth 2.0 (0) | 2021.06.01 |
๋์์ฑ Concurrency (+ ๋น๋๊ธฐ ํ๋ก๊ทธ๋๋ฐ, ๋์์ฑvs๋ณ๋ ฌ์ฑ) (0) | 2021.03.20 |
REST API๊ฐ ๋ญ๊ฐ์? - ์ธํฐํ์ด์ค, API, REST API, HTTP method (0) | 2021.03.17 |
Camel case, Kebab case, Snake case ๊ทธ๋ฆฌ๊ณ Pascal case (0) | 2021.03.17 |