2015년 12월 9일 수요일

Global Exception Handling

There is a way to handle the exception by using @ControllerAdvice

pom.xml


 4.0.0
 org.test.blog
 sample
 0.1.0
 
  org.springframework.boot
  spring-boot-starter-parent
  1.3.0.RELEASE
 
 
  1.7
 
 
  
   org.springframework.boot
   spring-boot-starter-web
  
  
   org.projectlombok
   lombok
   1.16.6
  
 

 
  
   
    org.springframework.boot
    spring-boot-maven-plugin
   
  
 



src/main/java/TestApplication

package org.test.blog;

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

@SpringBootApplication
public class TestApplication {

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

src/main/java/TestExceptionHandler

package org.test.blog.controller;

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.ResponseStatus;
import org.springframework.web.client.ResourceAccessException;

@ControllerAdvice
public class TestExceptionHandler {

    @ExceptionHandler(value = ResourceAccessException.class)
    @ResponseStatus(code = HttpStatus.CREATED,
                    reason = "you entered 1")
    public void resourceAccessException() {
    }

}

When you call the "exception/1", ResourceAccessException will be occurred,
and controllerAdvice will change the response to what you set before.

Result

GET http://localhost:8080/exception/1

201 Created
{
"timestamp": 1449728639528,
"status": 201,
"error": "Created",
"exception": "org.springframework.web.client.ResourceAccessException",
"message": "you entered 1",
"path": "/exception/1"
}

original source : https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

댓글 없음 :

댓글 쓰기