如何将RestController中引发的异常转移到调用RestEnd point的最终客户端?

我想了解如何将RESTEnd point中引发的异常“转移”给调用REST端点的客户端。

@GetMapping"/v1/xyz/{param}",produces = MediaType.APPLICATION_JSON_VALUE)

public ResponseEntity<String> doSomeWork() {

   if(normal) {
    // return value

  }
  else {

        throw new SomeException()
  }  
}

在正常流程中,它返回ResponseEntity。

我的疑问是,当此rest控制器引发异常时,该异常如何级联给调用了该剩余端点的客户端?

j445566321 回答:如何将RestController中引发的异常转移到调用RestEnd point的最终客户端?

异常将通过ResponseEntity通过以下方式传达给客户端:

import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.OK;

@RestController
public class MyController {

    @Autowired
    private MyServiceLayer service;

    @GetMapping"/v1/xyz/{param}",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> doSomeWork() {
        try {
            service.doSomeWork();
        } catch(SomeException ex) {
            return new ResponseEntity<>(ex.getMessage(),INTERNAL_SERVER_ERROR);
        }
            return new ResponseEntity<>("some string",OK);
    } 
}

我将使用一个服务层,如果操作失败,它将抛出一些异常。然后返回500响应,告诉客户有关此信息!

本文链接:https://www.f2er.com/2913073.html

大家都在问