春季启动。在一个应用程序中,@ Ccontroller和@RestController的错误不同

时间:2017-12-12 18:58:07

标签: spring rest spring-boot error-handling

我在一个应用程序中有正常的@Controller和@RestController。 如何在Json for REST中处理错误,并重定向到正常@Controller的错误页面?

1 个答案:

答案 0 :(得分:1)

您可以在控制器中使用Spring Annotation @ExceptionHandler,并在控制器逻辑中抛出异常。举一个简短的例子,我将使用Java的RuntimeException。您可以定义自己的异常并抛出它们

// your controller classes
@Controller
public class MyController {

  @ExceptionHanlder(RuntimeException.class)
  public String errorInController(){

   // for your custom page
   return "yourDefineErrorTemplatePage";

   // if you want to redirect to the default spring page
   // return "redirect:/error";
 }

 @RequestMapping("yourFirstEndpoint")
 public String getPage(){

    if(yourLogicHere){
         throw new RuntimeException("Display error page");
    }
    return "myPage";
 }
}

您的@RestController可能如下所示:

@RestController
public class RestControllerClass{

  @ExceptionHandler(RuntimeException.class)
  public ResponseEntity<Error> errorOccured(){

       // you can return just a String or define your own 'error object'
       Error error = new Error("Some error occured");
       return new ResponseEntity<Error>(error, Http.Status.NOT_FOUND);

 }

 @RequestMapping("yourSecondEndpoint")
 public ResponseEntity<YourEntity> getPage(){

    // the entity you want do return as json
    YourEntity yourEntity = new YourEntity();

    if(yourLogicHere){
         throw new RuntimeException("Display error page");
    }
    return new ResponseEntity<YourEntity>(yourEntity, HttpStatus.OK);
 }

}

错误对象的示例:

public class Error{

   private String errorMessage;

   public Error(String errorMessage){
      this.errorMessage = errorMessage;
   }
}

我希望这个小例能解决你的问题。

有关详细信息,请访问:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc