Following code generates exception as UserAlreadyExist.
Optional<User> userCheck = userRepository.findByUsername(createRequest.getUsername());
if(StringUtils.hasText(userCheck.get().getUsername())){
String errorMessage = "User already exist: "+ userCheck.get().getUsername();
throw new UserAlreadyExistException(errorMessage);
}
When i try to get error message from my react app with these codes i only get Internal server error message. My header contains header token and application/JSON header.
export const createUserService = (data) => {
return new Promise(((resolve, reject) => {
axios.post(USERS_BASE, data, getHeaderWithToken())
.then(function (response) {
resolve(response);
})
.catch(error=>{
console.log(error)//returns "Internal Server Error" message
console.log(error.response) // returns object with empty message field and other parameters.
reject(error)
})
}));
};
How can i get the error message i sent like
String errorMessage = "User already exist: "+ userCheck.get().getUsername();
throw new UserAlreadyExistException(errorMessage);
this is my UserAlreadyExistException class btw.
public class UserAlreadyExistException extends RuntimeException {
public UserAlreadyExistException(String message) {
super(message);
}}
You can return custom Response with #RestControllerAdvice for the custom exception you are throwing.
Please check the example below.
#RestControllerAdvice
public class ControllerExceptionHandler {
#ExceptionHandler(value = {UserAlreadyExistException.class})
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ErrorMessage userAlreadyExistException(UserAlreadyExistException ex, WebRequest request) {
ErrorMessage message = new ErrorMessage(
status,
date,
ex.getMessage(),
description);
return message;
}
}
It will be much easier for you to see the error in your Frontent application with a Response that you will return like this.
Related
If I use Throw new Error("User not found"), then it gives in response
{status:false,message:"User Not Found"}
But with status code 500, And I need Status 400 in Postman
custom Error using throw function
but if we use res.status(500).send({ status: false, message: "User not found" })
then it gives status code 400, And I need Status 400 in Postman . So, I need same status code in postman only.This is the problem. Tyler2P and Abin Bala , I followed your code but I am unable to get desired status code in postman status.
You can create a custom error class as below and throw it with appropriate message and httpCode. You can also add more properties. Then you can catch the custom error object using the catch block and get the required values.
class CustomError extends Error {
name;
httpCode;
message;
constructor(name,httpCode, message){
super(message);
this.name = name;
this.httpCode = httpCode;
this.message = message;
}
}
errorThrowingFunction.js:
//import the custom error class in the module that you //are going to use it.
errorThrowingFunction = () => {
const authToken = myCache.get("token");
if (!authToken) {
throw new CustomError('Error',401,'token missing');
} else {
return authToken;
}
}
index.js:
handler = () => {
try {
errorThrowingFunction();
} catch(error){
const response = {
statusCode: error.httpCode,
body: JSON.Stringify(error.message),
isBase64Encoded: false,
//add other headers
}
return response;
//if you are using this in rest service, the use below line
//return res.status(error.httpCode)send(response);
}
}
This is my controller
public IActionResult Privacy(int? id)
{
if(id.HasValue)
throw new Exception("privacy page exception");
return View(); ///working- redirected to Error view
}
[HttpGet]
public async Task<IActionResult> SearchCustomerPartial([FromQuery] CustomerSearch searchModel)
{
try {
var result = await _customerapiService.SearchCustomer(searchModel);
return PartialView("_CustomerList", result.Data);
}
catch ( Exception e)
{
return RedirectToAction("Index", "Error"); ---Not working it remains in same controller
}
}
Global exception handler
public static void UseGlobalExceptionHandler(this IApplicationBuilder app
, ILogger logger
, string errorPagePath
, bool respondWithJsonErrorDetails = false)
{
app.UseExceptionHandler(appBuilder =>
{
appBuilder.Run(async context =>
{
//============================================================
//Log Exception
//============================================================
var exception = context.Features.Get<IExceptionHandlerFeature>().Error;
string errorDetails = $#"{exception.Message}
{Environment.NewLine}
{exception.StackTrace}";
int statusCode = (int)HttpStatusCode.InternalServerError;
context.Response.StatusCode = statusCode;
//Check status code, if different redirect error page
context.Response.Redirect(errorPagePath); --- Redirect code
await Task.CompletedTask;
});
});
}
Problem:
I have 2 Methods Privacy() and SearchCustomerPartial() in controller.
My global exception handler working fine for Privacy it redirect to Error view when error.
But not not working for SearchCustomerPartial() (returns partial view)
if any exceptions in the SearchCustomerPartial() not redirected to Error view and showing Error in same page and overlap.
Below is the Error page
How to redirect to Error page in the partial view returns in the controller .. Am using Asp.net core 3.1
Kindly suggest..
EDIT:
My javascript Code
fetch(url + "?" + o)
.then(response => response.text())
.then(html => {
debugger
// console.log(html);
document.getElementById('partialresult').innerHTML = html;
})
.catch(err => {
debugger
console.log("Can’t access " + url + " response. Blocked by browser?" + err)
document.getElementById('partialresult').innerHTML = "";
});
Server returns 500 But it not coming under Catch in javscript..Kindly suggest
if Bad Request come from server how to handle in javascript
if any exceptions in the SearchCustomerPartial() not redirected to Error view and showing Error in same page and overlap.
Based on your code and requirement, you can try to modify the code like below.
fetch(url + "?" + o)
.then(function (response) {
//check if it is redirected to custom error page
if (response.redirected && response.url.indexOf("/Home/Error1")>0) {
response.text().then(function (html) {
document.write(html);
});
} else {
response.text().then(function (html) {
document.getElementById('partialresult').innerHTML = html;
});
}
})
I would like to keep all of error descriptions in a single .js file as a dictionary, so that I can display the appropriate description from the rest of my JavaScript web app. I am very new to JS web app development and I am wondering how to achieve this.
currently I have been trying this:
errorDesc.js:
var descriptions = {
errorCode00 : "description",
errorCode02 : "description",
errorCode03 : "description"
}
export function getResponseDescription(name) {
return descriptions[name];
}
main.js:
import {getResponseDescription} from "./errorDesc";
But in the console I get the following error:
Uncaught SyntaxError: Unexpected token {
I will suggest you have a file consist of error classes (used to set an error message and error name) which extend Error class and in the constructor assign the error message and error name to the object e.g.
class AuthorizationError extends Error {
constructor(message) {
super(message);
this.name = 'AuthorizationError';
this.message = message;
}
}
// classes of other error types
after that set, the status code based on the type of error and return e.g.
const errorHandler = (error, req, res, next) => {
const message = error.message || 'Something went wrong';
let status = null;
switch(error.name) {
case 'AuthorizationError':
status = 403;
break;
// other error types
}
res.status(status).json({ message });
}
wherever you encounter error create a new instance of the type of error class
next(new AuthorizationError('Username or password do not match'));
In the Axios document:
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
we know we can catch the error in the .catch() method.
But when I use the Django-Rest-Framework as the backend API provider. it only provide the data, there is no status in it:
You see the error:
{username: ["A user with that username already exists."]}
but in the browser, we can know the status code:
Before asking this question, I have read How can I get the status code from an http error in Axios?
this post.
But the post seems different with mine.
EDIT-1
In my Django-Rest-Framework project:
the view:
class UserCreateAPIView(CreateAPIView):
serializer_class = UserCreateSerializer
permission_classes = [AllowAny]
queryset = User.objects.all()
the serializer:
class UserCreateSerializer(ModelSerializer):
"""
user register
"""
class Meta:
model = User
fields = [
'username',
'wechat_num',
'password',
]
extra_kwargs = {
"password":{"write_only":True}
}
def create(self, validated_data):
username=validated_data.pop('username')
wechat_num = validated_data.pop('wechat_num')
password=validated_data.pop('password')
user_obj = User(
username=username,
wechat_num=wechat_num,
)
user_obj.set_password(password)
user_obj.save()
group=getOrCreateGroupByName(USER_GROUP_CHOICES.User)
user_obj.groups.add(group)
return validated_data
I find in the interceptors configuration:
Axios.interceptors.response.use(
res => {
return res;
},
error => {
return Promise.reject(error.response.data)
}
);
I was return the error.response.data directly, I could configure it to error.response, or error.
if I configure the error.response, then in the .catch() I can console like bellow:
console.log(response.data);
console.log(response.status);
console.log(response.headers);
I am using ionic 3 native HTTP to do a POST request to my backend server which returns JSON data but when I try to access the object from the variable I get an error:
[ts] Property 'InRepair' does not exist on type '{}'.
any
Not sure what I am doing wrong.
I made my POST request function a provider and here is the code for that
HttpProvider.ts
import { HTTP } from '#ionic-native/http';
#Injectable()
export class TekItapiProvider {
apiURL = 'myAPISeverURL';
constructor(private http: HTTP) {
}
doPost(url, data) {
var endpointURL = this.apiURL + url;
return new Promise((resolve, reject) => {
this.http.post(endpointURL, data, this.headers)
.then(data => {
resolve(data.data);
})
.catch(error => {
console.log(error.status);
reject(error);
})
})
}
}
This is where it is being called and where I try to access the object. In status I can access .completed because it gives me the error: [ts] Property 'InRepair' does not exist on type '{}'.
any
request.ts
this.httpProvider.doPost(myURL, '')
.then((status) => {
if (status.completed == 'Yes') {
}
},(err) => {
})
Do you guys know what I am doing wrong here?