๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๋ฐ˜์‘ํ˜•

GlobalExceptionHandler

package com.suri.farm.global.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {
    // 400 Bad Request
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleBadRequest(MethodArgumentNotValidException e) {
        e.printStackTrace();
        Map<String, String> error = new HashMap<>();
        error.put("message", "์ž˜๋ชป๋œ ์š”์ฒญ์ž…๋‹ˆ๋‹ค. ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ํ•˜์„ธ์š”");
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
    }

    // 500 Internal Server Error - ๊ทธ ์™ธ ๋ชจ๋“  ์˜ˆ์™ธ
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, String>> handleException(Exception e) {
        e.printStackTrace();
        Map<String, String> error = new HashMap<>();
        error.put("message", "์„œ๋ฒ„ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ํ•˜์„ธ์š”.");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
    }
}

์›๋ž˜ ์—๋Ÿฌ์ฝ”๋“œ๋Š” ๋”ฐ๋กœ ๋ณ€์ˆ˜๋กœ ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š”๋ฐ ๊ท€์ฐฎ์•„์„œ...

e.printStackTrace();๊ฐ€ ์—†์œผ๋ฉด ์ฝ˜์†”์— ๋ญ๋•Œ๋ฉ” ์—๋Ÿฌ๊ฐ€ ๋‚˜ํƒ€๋‚ฌ๋Š”์ง€ ์•ˆ๋‚˜ํƒ€๋‚œ๋‹ค.

๋ฐ˜์‘ํ˜•