提问者:小点点

如何使用spring异常处理发布REST更正错误状态代码


我正在尝试处理POST请求中丢失的json数据。我的控制器类

@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());
    }

}

扩展类:

public class StatusEndpointHandler {


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



    return status;
}

}

已实现的接口:

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

Status get(ID id);

Status create(T entity, BindingResult bindingResult);}

请看突出显示的部分,所以,当我试图通过邮差测试结果,我得到的状态为200 OK。我不知道怎么解决它。请帮我处理一下这种情况。如何获得正确的状态代码??


共3个答案

匿名用户

您应该将返回类型从@responseBody更改为responseEntity,这将允许您操作头,因此设置状态,这是文档中的一个片段

 @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);
 }

匿名用户

问题是处理字符串比较的代码,要比较字符串,必须使用equals,Postman还会传递空的testName和groupName

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

因此将代码更改为下面

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

    } 

还要为此编写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);
}

您还可以使用验证api在实体类中定义验证约束,在这种情况下,您需要将@valid添加到请求模型对象

@Entity
class TestMetrics {

    @Id
    Long id;

    @NotNull
    @NotEmpty
    @Column
    String groupName;

    @NotNull
    @NotEmpty
    @Column
    String testName;

    // Getters and Setters

}

匿名用户

在catch语句中,尝试通过

response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );

来源