Digking's cave

My First Blog Project (9) : Exception 처리 본문

Spring/My First Blog Project

My First Blog Project (9) : Exception 처리

디깅 2022. 12. 16. 17:55
728x90

hanler패키지 생성

handler/GlobalExceptionHandler.java

package com.cos.blog.handler;

import com.cos.blog.dto.ResponseDto;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

    @ExceptionHandler(value = IllegalArgumentException.class)
    public String handleArgumentException(IllegalArgumentException e){
        return "<h1>" + e.getMessage() +"</h1>";
    }


}

 

@ControllerAdvice

exception이 발생하면 이 class로 들어오게 한다.

 

 

모든 exception 한 번에 처리👇

package com.cos.blog.handler;

import com.cos.blog.dto.ResponseDto;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public String handleArgumentException(Exception e){
        return "<h1>" + e.getMessage() +"</h1>";
    }
}
반응형