简体   繁体   English

带有Java新行的自定义异常消息

[英]Custom Exception message with new line in Java

I am throwing a custom exception as below to UI 我正在向UI投掷如下的自定义异常

StringBuilder errorMessage = new StringBuilder("Error One Message"); 
String newlinetest = System.getProperty("line.separator");
                  // String sep = System.line.separator;
String secondErrorMessage = "Error Two message";
throw new ErrorWhileCreatingMessageException(errorMessage+"\r\n"+secondErrorMessage);

I need to add new line between two error messages before throwing. 我需要在抛出之前在两个错误消息之间添加新行。 I tried \\n, \\r\\n and line. 我试过\\ n,\\ r \\ n和行。 separator it didn't work. 分隔符不起作用。 Any help on this is much appreciated 对此有任何帮助非常感谢

I am using Angular JS in the UI. 我在UI中使用Angular JS。 I am displaying as below 我显示如下

<div ng-show="error != null">
    <div class="alert alert-danger" role="alert" ng-bind="error"></div>
</div>

Why dont you just read the content of the div you are inserting the error message in, and find/replace \\r\\n with a <br> 为什么你不只是阅读你插入错误信息的div的内容,并找到/替换\\r\\n与一个<br>

or just straight up try a <br> in that error message instead of \\r\\n, does that help? 或者直接尝试在该错误消息中使用<br>而不是\\ r \\ n,这有帮助吗?

如果您在HTML中显示结果,请尝试使用<br>替换\\ r \\ n

The idiomatic thing to do here is to return a proper error object from your rest service when an error happens, and split out the error type from the error message . 这里惯用的事情是在发生错误时从休息服务返回一个正确的错误对象 ,并从错误消息中分离出错误类型 This will require a new class and require you to send that over the wire, but you'll find it easier to deal with as you'll be able to properly populate values for error.type and error.message . 这将需要一个新类,并要求您通过网络发送,但您会发现它更容易处理,因为您将能够正确填充error.typeerror.message的值。

By default, Angular isn't going to allow you to render raw HTML in responses unless you regard it as unsafe. 默认情况下,Angular不允许您在响应中呈现原始HTML,除非您认为它不安全。 In 99% of the cases I've seen with Angular, that's exactly what you don't want to do. 在99%的情况我已经看到了角,这正是你不想做的事。

Alternatively...since exceptions are meant for you as a developer and error messages are meant for consumers, you may want to rethink what you're sending. 或者......因为例外对您而言是开发人员而错误消息是针对消费者的,您可能需要重新考虑您发送的内容。 You don't want to send across the stack trace or anything too specific to the end user, since they're not going to understand it. 你不想在整个堆栈跟踪或什么具体的最终用户发送,因为他们不会去了解它。 It would be best to select a generic message which explains what the issue is in general, and what they're doing to fix it. 最好选择一个通用消息来解释一般问题是什么,以及他们正在做些什么来解决它。 For some inspiration, Stack Overflow's error page does a decent job of keeping us as clients shielded from the actual error. 对于一些灵感, Stack Overflow的错误页面可以很好地保护我们的客户端免受实际错误的影响。

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

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