I'm having an issue in the using statement. Error is posted below. What do you guys think makes the program generate that error?
public JsonResult Save_Record(UserModels model)
{
using (var con = new OracleConnection(ConfigurationManager.ConnectionStrings["DBEntities"].ConnectionString))
{
...
}
}
Here's the error in the using line:
An exception of type 'System.ArgumentException' occurred in Oracle.DataAccess.dll but was not handled in user code
Additional information: 'metadata' is an invalid connection string attribute
Related
I am refactoring an ASP.NET WEB API solution that uses Odata.
When dealing with errors I would like to provide a custom error payload which is defined in my CustomException class.
The issue is that when I make a bad request the generated response is the ODataException error payload which contains some confidential information that I don't want exposed and also the stack trace.
I need to modify this Odata payload and replace it with my own.
So far what I've tried is to use Exception Filters applied on Controller level and also tried to register an Exception Handler on global level. None of these worked.
Any help would be greatly appreciated.
I was able to resolve it with Exception Filter, I was using the wrong method before:
public class CustomExceptionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
ErrorContentResponse error = new ErrorContentResponse();
var response = new HttpResponseMessage(actionExecutedContext.Response.StatusCode)
{
Content = new ObjectContent<ErrorContentResponse>(error, new JsonMediaTypeFormatter())
};
actionExecutedContext.Response = response;
}
}
I have implemented controlleradvice in my spring mvc project. Am able to see proper response but unable to find my stack trace.
Here is my code, can any one tell me what should i do to get stack trace.....
#ExceptionHandler(Exception.class)
public ResponseEntity<?> handleException(final Exception exception) {
err.setErrorMessage("server_error");
return new ResponseEntity<ErrResp>(err,
HttpStatus.OK);
}
Try:
exception.getStackTrace();
You can assign this to a variable if needed or use the below to see stacktrace in console:
exception.printStackTrace();
i'm developing a WebApi selfhost application with oData controllers.
I have some base controller with method get
public class ODataControllerBaseClientFilter<T> : ODataControllerBase<T> where T : class, IClientId, new()
{
public ODataControllerBaseClientFilter(IDataService<T> service) : base(service)
{
}
public override IQueryable<T> Get(string query = null)
{
var a = base.Get(query).ToArray();
return base.Get(query);
}
}
There is an error in mapping EF entity to database, so if I execute query with code
var a = base.Get(query).ToArray();
EF will generate exception and return error to the client correctly.
But if I will remove this line and just return IQuerible object, there will no any exception and no any result at client! How can i resolve this problem?
UPD: text of the error
{"Unable to determine composite primary key ordering for type
'Lk.Search.Data.Models.ReportClient'. Use the ColumnAttribute (see
http://go.microsoft.com/fwlink/?LinkId=386388) or the HasKey method
(see http://go.microsoft.com/fwlink/?LinkId=386387) to specify an
order for composite primary keys."}
UPD2: I use jquery ajax to get data from oData service (for testing I just use get request from browser)
This my web service code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.Sql;
using System.Data.SqlClient;
namespace DBwebService
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://kse.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
string ConnectionString = "Data Source=Shumaila-PC;Initial Catalog=kse;Persist Security Info=True;User ID=sa;Password=sa";
public SqlConnection Conn;
[WebMethod]
public void SqlConn()
{
Conn = new SqlConnection(ConnectionString);
// Conn.Open();
}
//catch (SqlException ex)
//{
// //Console.WriteLine( "Connection Unsuccessful " + ex.Message);
//}
}
}
I need to return my sql connection object so that i can call it in my asp.net pid roject. but when i did
public SqlConnection SqlConn()
and
return.Conn();
this gives me the following error
Server Error in '/' Application. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not create type 'DBwebService.WebService1'.
Source Error:
Line 1: <%# WebService Language="C#" CodeBehind="WebService1.asmx.cs" Class="DBwebService.WebService1" %>
Source File: /WebService1.asmx Line: 1
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1 --. Metadata contains a reference that cannot be resolved: 'http://localhost:50387/WebService1.asmx'. The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (application/soap+xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: ' Server Error in '/' Application. Parser Error '. The remote server returned an error: (500) Internal Server Error. If the service is defined in the current solution, try building the solution and adding the service reference again.
My God are you serious? You should not even think to return a connection from a service. you should return the data you load with a query which is executed using that connection. that is, move all the logic of what you want to do with the connection in the calling code inside a DAL class library and return the results only.
Your web service should expose a method which accepts the signup data as an argument to the method. The service can then commit that data to the database and then return an Ack/Nack response to the UI.
HMM come to think of it connection object is not serialized you have to declare your object as serialize-able only to do the above task, only primitive types are auto serialize-able.
I'm migrating some servlets over to the Spring framework, using Spring MVC. Currently in each servlet we authenticate the user and if the authentication fails we do this:
if (authfailed)
{
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"You are not authorized.");
return;
}
On the front end is a YUI-based application, and when an error status is returned the "failure" callback displays a dialog with the error message given above.
I know in my controller I can get the response object and call sendError, but is that the best way to handle this? sendError also throws an IOException so I'd have to catch that - a bit of annoying code to insert in every method of every controller.
I have the same problem handling exceptions - the servlets have try-catch blocks that call sendError in the catch method. I know I can mark my exception handlers with
#ExceptionHandler
#ResponseStatus(value = HttpStatus.NOT_FOUND)
but doesn't the exception handling class need to be in each controller class?
Finally, if the exception happens in a service called from a controller, does the exception bubble up to the controller or should I handle the exception in the service (thus pushing these exception handling issues into the service layer)?
This seems more difficult than it should be, but as with many things in Spring it's likely I don't understand what's going on. All I want to do is to send an error status and message back in the response!
Thanks,
Paul
It looks like you have the most of the answers in your question itself :)
To reiterate,
Have the controller like this
#RequestMapping("/test")
public String verifyAuth(HttpServletRequest request) throws NotFoundException {
String id = request.getParameter("id");
if (id == null)
throw new NotFoundException("Id not found in the request");
return "success";
}
Declare the exception class in NotFoundException.java,
#ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Id Not Found")
public class NotFoundException extends Exception {
public NotFoundException(String msg) {
super(msg);
}
}
This exception class need not be every controller class. Declare it as public class and import it in every required controller.
This is one way of doing it. If you like the non-spring style, declare HttpServletResponse in every controller arguments and do
#RequestMapping("/test")
public String verifyAuth(HttpServletRequest request, HttpServletResponse response) {
...
try {
response.sendError(..)
catch(..) {}
}
Or you can use views to show error message,
#RequestMapping("/test")
public String verifyAuth(HttpServletRequest request, Map<String, Object> map){
String id = request.getParameter("id");
if (id == null) {
map.put("status", HttpStatus.NOTFOUND);
map.put("reason", "Id Not Found");
return "error"
}
return "success";
}
Make sure your viewResolver is configured correctly and in the error.jsp to get the error string, you could say.
<body>
${status} ${reason}
</body>
Define error.jsp with nice css for all kind of errors you would expect.
These are not the only ways. With spring you have freedom to do anything. I have seen few ppl rendering json object for error message.
To answer your another question of if the error happens in the service called by the controller is depend on your scenario. For example you are trying to read the user store, if the user store not available error happens, I would handle there itself to read from another replica user store if one available and If I found user does not exist I would leave the exception to the controller to throw.