Spring3 and REST Integeration(VIII)REST ERROR Handler and JSON Mapper Infinite

本文介绍如何在REST API中处理错误消息,通过自定义异常类和控制器处理程序实现。同时解决JSON映射无限递归问题,使用Jackson库的@JsonIgnore注解避免循环引用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring3 and REST Integeration(VIII)REST ERROR Handler and JSON Mapper Infinite

First, how can I handle the REST error message in my REST API.
There is an example. In my get method in Person Conroller, I try to make a throw Exception like this:
if (id.equalsIgnoreCase("13")) {
thrownew JsonServiceException("101",
"Id can not be 13. Because I do not like it.");
}

The JsonServiceException will be a simple exception class extends Exception:
package com.sillycat.easyrestserver.exception;

publicclass JsonServiceException extends Exception {

privatestaticfinallongserialVersionUID = -2949102718021710130L;

private String errorCode;
private String errorMessage;

public JsonServiceException(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}

public String getErrorCode() {
returnerrorCode;
}

publicvoid setErrorCode(String errorCode) {
this.errorCode = errorCode;
}

public String getErrorMessage() {
returnerrorMessage;
}

publicvoid setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

The handler in controller will be as follow:
@ExceptionHandler(JsonServiceException.class)
publicvoid handleJsonServiceException(JsonServiceException exception,
HttpServletResponse response) throws IOException {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
exception.getErrorMessage());
}

The test implementation will be as follow:
publicvoid throwJSONError() throws Exception {
person.setId(13);
Mockito.when(mockPersonService.get(13)).thenReturn(person);

MockMvcBuilders
.standaloneSetup(personController)
.build()
.perform(
MockMvcRequestBuilders.get("/person/13").accept(
MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}

I make my objects like these, person will have one company, but company will have many persons. The mock object will be as follow:
person = new Person(3, "person3");
Person person1 = new Person(1, "person1");

Company company1 = new Company(1, "company1");

List<Person> personList = new ArrayList<Person>();
personList.add(person);
personList.add(person1);
company1.setPersons(personList);

person.setCompany(company1);

I execute the same junit test case, I will get these error messages.
error message:
org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.sillycat.easyrestserver.model.Company["persons"]->java.util.ArrayList[0]->com.sillycat.easyrestserver.model.Person["company"]->com.sillycat.easyrestserver.model.Company["persons"]->java.util.ArrayList[0]->com.sillycat.easyrestserver.model.Person["company"]-

That is because of infinite json mapper here. So the solution for these kind of problem will be the annotation supported in latest jackson lib.
@JsonBackReference("Company-Person")
public Company getCompany() {
returncompany;
}

and

@JsonManagedReference("Company-Person")
public List<Person> getPersons() {
returnpersons;
}

That is it.

references:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值