Bibi's DevLog ๐Ÿค“๐ŸŽ

HTTP Response Body์— ์˜ˆ์™ธ error message ์ง€์ •ํ•ด ๋ณด๋‚ด๊ธฐ ๋ณธ๋ฌธ

๐Ÿ–ฅ BE ๋ฐฑ์—”๋“œ

HTTP Response Body์— ์˜ˆ์™ธ error message ์ง€์ •ํ•ด ๋ณด๋‚ด๊ธฐ

๋น„๋น„ bibi 2021. 4. 30. 19:44

Http 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