我在一个应用程序中具有正常的@Controller和@RestController。
如何处理Json for REST中的错误,并重定向到普通@Controller的错误页面?
最佳答案
您可以在 Controller 中使用Spring Annotation @ExceptionHandler并在 Controller 逻辑中引发Exceptions。举一个简短的例子,我将使用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
关于spring - Spring 启动。在一个应用程序中为@Ccontroller和@RestController处理不同的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47779724/