简体   繁体   English

如何使用Spring Exception处理发布REST正确的错误状态代码

[英]How to POST REST correct error status code using Spring Exception handling

I'm trying to handle missing json data in a POST request. 我正在尝试处理POST请求中缺少的json数据。 My controller class 我的控制器班

@Controller
@RequestMapping("/testMetrics")

public class TestMetricsEndPoint extends StatusEndpointHandler implements RestEndPoint<TestMetrics,String> {

@Autowired
private ObjectMapper mapper;

@Autowired
private TestMetricsService testMetricsService;

@Override
public Status get(String id) {
    // TODO Auto-generated method stub
    return null;
}


@Override
@RequestMapping(method = RequestMethod.POST,consumes = "application/json", produces = "application/json")
public @ResponseBody Status create(@RequestBody TestMetrics core, BindingResult bindingResult) {
    try {
    if(bindingResult.hasErrors()){
        throw new InvalidRequestException("Add failed, Please try again ", bindingResult);
    }
    if((core.getGroupName()==""||core.getGroupName()==null)&&(core.getTestName()==null||core.getTestName()=="")){

            throw new MissingParametersException(HttpStatus.BAD_REQUEST.value(),"Please provide all necessary parameters");
        } 
    TestMetrics dataObject = testMetricsService.create(core);
    return response(HttpStatus.CREATED.value(),dataObject);
    }catch (MissingParametersException e) {
        return             response(HttpStatus.BAD_REQUEST.value(),e.getLocalizedMessage());
    }

}

Extended class: 扩展类:

public class StatusEndpointHandler {


public Status response(Integer statusCode,Object data){
    Status status = new Status();
    status.setData(data);
    status.setStatus(statusCode);



    return status;
}

}

Implemented interface: 实现的接口:

 public interface RestEndPoint<T extends SynRestBaseJSON, ID extends    Serializable> {

Status get(ID id);

Status create(T entity, BindingResult bindingResult);}

Result: 结果: 在此处输入图片说明

Please look at the highlighted part So, when i tried to test the result through POSTMAN, i'm getting status as 200 OK. 请查看突出显示的部分。因此,当我尝试通过POSTMAN测试结果时,我的状态为200 OK。 I have no idea hot to solve it. 我不知道要解决这个问题。 please help me with this situation. 请在这种情况下帮助我。 How to get the correct status code.? 如何获取正确的状态码?

You should change your return type from @ResponseBody to ResponseEntity which will allow you to manipulate headers, therefor set the status, this is a snippet from the docs 您应该将返回类型从@ResponseBodyResponseEntity ,这将允许您操作标头,从而设置状态,这是文档的摘录

 @RequestMapping("/handle")
 public ResponseEntity<String> handle() {
   URI location = ...;
   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.setLocation(location);
   responseHeaders.set("MyResponseHeader", "MyValue");
   return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
 }

In your catch statement, try to set the status through 在您的catch语句中,尝试通过以下方式设置状态

response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );

Source 资源

The problem is with your code handing the string comparison, to compare strings you have to use equals , from Postman also you are passing empty testName and groupName 问题是您的代码进行了字符串比较,要比较必须使用equals字符串,还需要从Postman中传递空的testName和groupName。

    if ((core.getGroupName() == "" || core.getGroupName() == null) && (core.getTestName() == null || core.getTestName() == "")) {
    }

so change your code to below 所以把你的代码改成下面

    if ((core.getGroupName() == null || core.getGroupName().trim().isEmpty()) && (core.getTestName() == null || core.getTestName().trim().isEmpty())) {

    } 

also write an ExceptionHandler for this 也为此编写一个ExceptionHandler

@ExceptionHandler({ MissingParametersException.class })
public ModelAndView handleException(ServiceException ex, HttpServletResponse response) {
    response.setStatus(HttpStatus.BAD_REQUEST.value());
    ModelMap model = new ModelMap();
    model.addAttribute("message", ex.getMessage());
    return new ModelAndView("error", model);
}

You can also define validation constrains in entity class using validation api, in this case you need to add @Valid to the request model object 您还可以使用验证API在实体类中定义验证约束,在这种情况下,您需要将@Valid添加到请求模型对象

@Entity
class TestMetrics {

    @Id
    Long id;

    @NotNull
    @NotEmpty
    @Column
    String groupName;

    @NotNull
    @NotEmpty
    @Column
    String testName;

    // Getters and Setters

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM