这是NullPointerExceptionMapper类
package com.sample.Exceptionhandler;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import response.Message;
@Provider
public class NullPointerExceptionMapper implements ExceptionMapper<NullPointerException> {
public Response toResponse(NullPointerException ex) {
Message message=new Message(500,ex.getMessage(),200);
return Response.status(Status.NOT_FOUND).entity(message)
.build();
}
}
这是Message类
package response;
public class Message {
private int status;
private String message;
private int code;
public Message() {
}
public Message(int status, String message, int code) {
super();
this.status = status;
this.message = message;
this.code = code;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
这是Controller方法
@RequestMapping(value = "/getOrder", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<PurchaseOrderHeaderDto> getOrders(){
String exceptionOccured="NULL_POINTER";
if(exceptionOccured.equalsIgnoreCase("NULL_POINTER")){
throw new NullPointerException("Null Pointer Exception");
}
return purchaseImpl.GetPurchaseOrder();
}
我无法处理抛出的异常,并且正在使用JAX-RS对其进行处理,但是它无法正常工作,欢迎任何建议,可以帮助我解决该异常。
答案 0 :(得分:1)
您正在将JAX-RS与Spring MVC混合使用。您的控制器代码是Spring MVC,而您尝试使用fetch(
'http://localhost:8888/magento/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=name&searchCriteria[filter_groups][0][filters][0][value]=product name',
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authentication: 'Bearer fwynACCESS_TOKENbal9tfr'
}
}
)
.then((res) => {
if (res.status !== 200 && res.status !== 204)
reject({ message: 'There was an error with the products service' })
resolve(res.json())
})
.catch((err) => reject(err))
进行异常处理的尝试是JAX-RS。这是两个完全不同且不兼容的框架。对于Spring MVC,您想使用@ControllerAdvice
类。