[Spring Boot #16] 스프링 ExceptionHandler

 

스프링 부트 ExceptionHandler

  • 스프링부트에서 ExceptionHandler를 기본적으로 등록하여 Exception을 처리하고 있다.
  • 기본 예외 처리기는 스프링에서 자동적으로 등록하는 BasicErrorController에서 관리한다.(에러 발생 시 JSON 형식으로 리턴한다)
  • 커스텀 Exception 핸들러, 커스텁 Exception 클래스를 만들어서 예외를 처리 할 수 있다.
  • Http Status 코드에 맞게 예외 발생 시 html 문서를 클라이언트에게 전송할 수 있다.

소스코드

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
package com.example.demo;

public class AppError {

    String message;
    String reason;

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getReason() {
        return reason;
    }
    public void setReason(String reason) {
        this.reason = reason;
    }
}
package com.example.demo;

public class SampleException extends RuntimeException { }
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SampleController {

    @GetMapping("/hello")
    public String hello() {
        throw new SampleException();
    }

    @ExceptionHandler(SampleException.class)
    public @ResponseBody AppError sampleError(SampleException e) {
        AppError appError = new AppError();
        appError.setMessage("error.app.key");
        appError.setReason("Critical Issue");
        return appError;
    }
}
  • /hello 요청이 왔을 때 SampleException을 발생시킨다. 이때, @ExceptionHandler 어노테이션이 해당 예외를 받아서 처리할 수 있다.

결과화면

예외 발생 시 HTML 문서를 사용자에게 반환하기

HTML문서

  • HTML문서를 작성할 시 HTTP Status 코드에 맞게 Html 문서를 작성해야 한다.
  • HTML문서의 파일명이 상태코드와 같거나 아니면 5xx와 같이 패턴을 맞추어서 만들어야 한다.
<!-- 404.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

    <h1>Hello 404</h1>

</body>
</html>
<!-- 5xx.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<h1>Hello 5xx Error</h1>

</body>
</html>

소스

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SampleController {

    @GetMapping("/hello")
    public String hello() {
        throw new SampleException();
    }

    /*
     * @ExceptionHandler(SampleException.class) public @ResponseBody AppError
     * sampleError(SampleException e) { AppError appError = new AppError();
     * appError.setMessage("error.app.key"); appError.setReason("Critical Issue");
     * return appError; }
     */

}

  • Root(/) 를 처리하는 코드를 만들지 않아서 No Found가 리턴되고 그에맞춰 404.html 이 반환된다.

  • /hello 요청을 처리하는 코드를 작성했지만 예외를 발생했기 때문에 505가 리턴되고 그에 맞춰서 5xx.html 이 반환된다.

댓글

Designed by JB FACTORY