Unable to catch MySqlException [Entity Framework WebAPI] - mysql

Code looks like this
public HttpResponseMessage PostUser(User user)
{
if (ModelState.IsValid)
{
try
{
db.Users.Add(user);
db.SaveChanges();
}
catch (MySqlException e)
{
....
}
}
}
WebServer return 500 Intenal due to duplicate Key, but never entered catch block.
I want to know how to catch MySqlException at above code.
ExceptionMessage: "Duplicate entry 'TEST2' for key 'IX_User'"
ExceptionType: "MySql.Data.MySqlClient.MySqlException"
StackTrace:
MySql.Data.MySqlClient.MySqlStream.ReadPacket()
MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
MySql.Data.MySqlClient.MySqlDataReader.NextResult()
MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
MySql.Data.Entity.EFMySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()"

You can handle it by SQLException like this:
// your class code
try{
// do your work
}catch(SQLExcepetipn e){
// handle it
}
There is no MYSQL Exception class.

Related

Handling CompressorException in Java8 Streams

I have a static method for reading .bz2 files, it throws checked IOException and org.apache.commons.compress.compressors.CompressorException. The function signature is:
private static MyClass readFile(String fileName) throws IOException, CompressorException{
//…
}
Trying to use this method outright with Java8 streams gets compile time errors in Intellij;
unhandled exceptions: java.io.IOException, org.apache.commons.compress.compressors.CompressorException
So following advice from here, among others, I’ve tried the following but am stuck on how to handle the CompressorException object. Following it’s ctor I’ve tried as below but Intellij still complains the CompressorException is unhandled:
files.stream().forEach(i -> {
try{
readFile(i);
} catch (IOException e){
throw new RuntimeException(e);
} catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
});
Thanks
As #JB Nizet mentioned in the comment, you cannot throw any Exception from the lambda function inside foreach function.
You need to replace your current implementation:
catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
to either the following or not throw the RuntimeException at all.
catch (Throwable ex){
throw new RuntimeException("compressorException", ex);
}
The reason for the above behaviour is that the Stream.foreach() method has the following signature and doesn't throw any exception as part of the signature.
void forEachOrdered(Consumer<? super T> action)

Exception handling - Try Catch ambiguous behaviour (??)

This is My code
from("direct:test-POST")
.doTry()
.process(new Processor() {
#Override
public void process(Exchange arg0) throws Exception {
throw new NullPointerException(" Null value");
}
})
.doCatch(NullPointerException.class)
.log("${exception}") // This Prints NullPointer Exception
.process(new Processor() {
#Override
public void process(Exchange arg0) throws Exception {
System.out.println( arg0.getException() ); //This prints Null
}
})
.end();
Am using jetty:run to run this camel route.
How do I catch the exception. It prints the exception correct in log. but inside the processor, the exception is null. what am I missing
I would think the exception is found on a property on the exchange. Something like:
Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, NullPointerException.class);
assertNotNull(caused);

Get exception information in mule catch exception strategy

I am using catch exception strategy in my mule flow(v3.7.3).If an exception is thrown in my flow .I want to retrieve the exception in catch exception strategy.
Mule exception flow:
<choice-exception-strategy
doc:name="Choice Exception Strategy">
<catch-exception-strategy
when="exception.causedBy(com.nc.exception.NcException)"
doc:name="Notification Center Exception Strategy">
<custom-transformer
class="com.zoto.nc.transformer.json.ExceptionTransformer" doc:name="Exception Transformer">
</custom-transformer>
</catch-exception-strategy>
</choice-exception-strategy>
In my ExceptionTransformer.java i want to handle the exception and get the exception object(to print the stacktrace)
ExceptionTransformer.java
public class ExceptionTransformer extends AbstractMessageTransformer {
private static org.apache.log4j.Logger LOG = Logger.getLogger(ExceptionTransformer.class);
#Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
// Need caught exception trace here.
try {
LOG.info("Initiating Transformer for Exception Response" + message.getPayloadAsString());
} catch (Exception e2) {
e2.printStackTrace();
}
LOG.info("Request landed at :" + new Date());
return message.getPayload();
}
Is there a way to get the exception stacktrace in the ExceptionTrasformer class?
What you should do is ask the MuleMessage for it's ExceptionPayload, which has the thrown exception where you can get the trace. That is message.getExceptionPayload().

add data in mysqldatabase using C#

Is my first time to using mysql as the backend for my ASP.NET application.
Am trying to Insert data into the table, but I keep having this error.
I have install the mysql connector. Can some one tell me where am doing wrong.
here is the error:
MySql.Data.MySqlClient.MySqlException was unhandled by user code
HResult=-2147467259
Message=You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Source=MySql.Data
ErrorCode=-2147467259
Number=1064
StackTrace:
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
at Agohealth.Requestlab.btnsubmit_Click(Object sender, EventArgs e) in C:\Users\PC3\Documents\Visual Studio 2010\Projects\Agohealth\Agohealth\LabRequest.aspx.cs:line 38
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace hiredad
{
public partial class Requestlab : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
string connectionstring = ConfigurationManager.ConnectionStrings["LocalMySqlServer"].ConnectionString;
using (MySqlConnection conn = new MySqlConnection(connectionstring))
{
MySqlCommand cmd = new MySqlCommand();
conn.CreateCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText=("INSERT INTO labrequest (Examination,TestName,RequestCode,PatientNumber,Date,Doctor)"
+ ("VALUES (?Examination,?TestName,?RequestCode,?PatientNumber,?Date,?Doctor"));
cmd.Parameters.Add("?Examination", MySqlDbType.VarChar).Value = DropDownList1.SelectedValue;
cmd.Parameters.Add("?TestName", MySqlDbType.VarChar).Value = dlistlabtestname.SelectedValue;
cmd.Parameters.Add("?RequestCode", MySqlDbType.VarChar).Value = txtrequestcode.Text;
cmd.Parameters.Add("?PatientNumber", MySqlDbType.VarChar).Value = txtreginum.Text;
cmd.Parameters.Add("?Date", MySqlDbType.Date).Value = labdate.Text;
cmd.Parameters.Add("?Doctor", MySqlDbType.VarChar).Value = txtdoctor.Text;
cmd.ExecuteNonQuery();
Message.Text = "Sucessfully inserted!";
}
}
}

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object?

I am using liferay 6.1 and created my custom portlet and in that I am using custom query which directly get the records from database with the following ....
public List<DashBoardBean> GetPieChartDataForCampaignbyOrganization(
ThemeDisplay pThemeDisplay) {
log.info("In GetPieChartDataForCampaignbyOrganization ");
Context CtxObj;
long pParentOrgId;
ResultSet advResultSet = null;
List<DashBoardBean> dashboardbeanObjList = new ArrayList<DashBoardBean>();
try {
CtxObj = new InitialContext();
DataSource DsObj = (DataSource) CtxObj
.lookup("java:comp/env/jdbc/Liferay");
Connection ConObj = DsObj.getConnection();
Statement sStmtObj = ConObj.createStatement();
advResultSet = sStmtObj
.executeQuery("MY CUSTOM QUERY WILL BE HERE");
while (advResultSet.next()) {
DashBoardBean dashboardbeanObj = new DashBoardBean();
dashboardbeanObj
.setsOrganizationName(advResultSet.getString(1));
dashboardbeanObj.setlOrganizationCount(advResultSet.getLong(2));
dashboardbeanObjList.add(dashboardbeanObj);
}
} catch (NamingException e) {
// TODO Auto-generated catch block
dashboardbeanObjList = null;
e.printStackTrace();
} catch (SQLException e) {
dashboardbeanObjList = null;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.info("Leave GetPieChartDataForCampaignbyOrganization ");
return dashboardbeanObjList;
}
Above is code snippet of one of my function... I have more then 5 function with the same structure... Just SQL query is different in function...
Now Problem is that I have to call more then 5 functions like this in page load...so when I use to reload the page frequently... It gives me error as following...
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:114)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at emenu.advertise.appbl.DashBoardCustomQuery.GetPieChartDataForCampaignStatus(DashBoardCustomQuery.java:112)
at emenu.advertise.appbl.DashBordBL.GetPieChartDataForCampaignStatus(DashBordBL.java:292)
at emenu.advertise.portlet.RestaurantPortlet.serveResource(RestaurantPortlet.java:402)
at com.liferay.portlet.FilterChainImpl.doFilter(FilterChainImpl.java:118)
at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:71)
at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:72)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:73)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.liferay.portlet.InvokerPortletImpl.invoke(InvokerPortletImpl.java:531)
at com.liferay.portlet.InvokerPortletImpl.invokeResource(InvokerPortletImpl.java:626)
at com.liferay.portlet.InvokerPortletImpl.serveResource(InvokerPortletImpl.java:436)
at com.liferay.portal.action.LayoutAction.processPortletRequest(LayoutAction.java:1075)
at com.liferay.portal.action.LayoutAction.processLayout(LayoutAction.java:719)
at com.liferay.portal.action.LayoutAction.execute(LayoutAction.java:249)
at ............................
.......java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1171)
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
... 131 more
09:24:11,163 INFO [http-bio-8080-exec-5][DashBoardCustomQuery:665] Leave GetHighestClickRestaurantName
09:24:11,163 INFO [http-bio-8080-exec-5][DashBoardCustomQuery:304] Leave GetLineChartDataForHighestClickedByRestaurant
09:24:11,164 INFO [http-bio-8080-exec-5][DashBordBL:166] Leave GetLineChartDataByRestaurant From DashBordBl
I know that I have done something wrong... But I don't know where... maybe it's because its SQL connection just lost from the server/// is it because I am not closing connection... Please help me... And correct me where am wrong... I had just given one example of my function the way I used to fetch data from other function...
i have just found the solution as i have never closed the connection object after execution of query.i have done as follows which works for me after try catch block...
finally {
try {
if(CtxObj!=null) {
CtxObj.close();
}
if(sStmtObj!=null){
sStmtObj.close();
}
if(ConObj!=null){
ConObj.close();
}
} catch (NamingException e) {
// TODO Auto-generated catch block
log.info(e);
} catch (SQLException e) {
// TODO Auto-generated catch block
log.info(e);
}
}