Java 如何编写自定义运行时异常以发送包含2个自定义信息的json响应?
背景是: 我正在创建一个上传csv服务,当我对内容进行一些验证时,我想抛出一个自定义运行时异常,其中包含错误消息和问题所在行 我现在得到的是:Java 如何编写自定义运行时异常以发送包含2个自定义信息的json响应?,java,Java,背景是: 我正在创建一个上传csv服务,当我对内容进行一些验证时,我想抛出一个自定义运行时异常,其中包含错误消息和问题所在行 我现在得到的是: public class NotValidCsvException extends RuntimeException { private static final long serialVersionUID = 1L; private Integer _line; public NotValidCsvException(final Stri
public class NotValidCsvException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Integer _line;
public NotValidCsvException(final String message, final Integer line) {
super(formatMessage(message, line));
}
public static String formatMessage(String message, Integer line) {
return new StringBuilder()
.append("{message: ")
.append("'")
.append(message)
.append("'")
.append(", ligne: ")
.append("'")
.append(line)
.append("'")
.append("}").toString();
}
}
但问题是我得到的回答是:
{"timestamp":1511785651810,"status":500,"error":"Internal Server Error","exception":"com.sstrn.pa.service.impl.exception.NotValidCsvException","message":"{"message": "message_import_csv_undefined_thing", "line": 0}"}
但我想要的是:
{"timestamp":1511785651810,"status":500,"error":"Internal Server Error","exception":"com.sstrn.pa.service.impl.exception.NotValidCsvException","message":"message_import_csv_undefined_thing", "line": 0}
为此,我创建了接口attributeEnabled,它由我的NotValidCsvException实现
public interface AttributeLineEnabled {
public Integer getLine();
}
public class NotValidCsvException extends RuntimeException implements AttributeLineEnabled {
private static final long serialVersionUID = 1L;
private Integer _line;
public NotValidCsvException(final String message) {
super(message);
}
public NotValidCsvException(final String message, Integer line) {
super(message);
_line = line;
}
public Integer getLine() {
return _line;
}
public void setLine(final Integer line) {
_line = line;
}
}
然后我创建了一个扩展DefaultErrorAttributes并实现ErrorAttributes的控制器。
此控制器覆盖设置jsonResponse的getErrorAttributes方法
public class BaseErrorAttributes extends DefaultErrorAttributes implements ErrorAttributes {
private static final String LINE = "line";
public BaseErrorAttributes() {
super();
}
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
Throwable error = getError(requestAttributes);
if (error instanceof AttributeLineEnabled) {
AttributeLineEnabled attributeLineEnabled= (AttributeLineEnabled) error;
errorAttributes.put(LINE, attributeLineEnabled.getLine());
}
return errorAttributes;
}
}
嗯。。。与创建任何其他组合对象的方式相同,但这一个扩展了(运行时)异常?但想法是在json响应firedok中使用“errCode”。。和我看不出问题欢迎使用堆栈溢出!请看一看,仔细阅读,特别是你的问题没有提到JSON,或者是一个“响应”被“炒鱿鱼”;也不清楚为什么你链接的问题没有回答你的问题。问题是我想得到信息,以及我前面的响应中可访问的自定义字符串,这样我就可以执行如下操作:response.message和response.errCode
private BaseErrorAttributes _baseErrorAttributes;
// getter and setter too