控制器SpringMVC处理错误 [英] Error handling on controller SpringMVC

查看:98
本文介绍了控制器SpringMVC处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在jax-rs和spring mvc开发一个应用程序。
我想在每次出现默认错误时通知我的客户,如
400,403,404,405和415。



控制器



  @Controller 
@RequestMapping(/ customer)
public class CustomerController {

@Autowired
CustomerService customerService;

// ........ xxxxxx .............. xxxxxxx ................ xxxxxxx ............. //


@CrossOrigin
@RequestMapping(value =/,
method = RequestMethod .GET,
produce = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String fetchCustomer()throws JsonProcessingException {
return new ObjectMapper()。writeValueAsString(customerService.fetchAllCustomer());
}

// ........ xxxxxx .............. xxxxxxx ........... ..... xxxxxxx ............. //

}



客户端



  $ http({
method:GET,
contentType:application / json,
url:baseUrl +'/ customer'
})。success(function(response){
console.log(response);
//你也可以使用
console.log(JSON.stringify(response);
})。error(function(response){
console.log(response);
});

当我从客户端请求一个服务时,我想用状态代码和自定义消息。



示例



当我在控件和客户端上定义method = post时,我发送请求作为get服务应该返回消息,如

 错误:{
状态码:405,
消息:无效方法
url:错误/ 405
}


解决方案

一个String,但返回一个org.springframework.http.ResponseEntity。
您可以向此对象添加状态代码

  ResponseEntity< String> responseEntity = new ResponseEntity< String>(这是一个响应,HttpStatus.INTERNAL_SERVER_ERROR); 
return responseEntity;

所以你的方法签名也会如下更改

  @RequestMapping(value =/,method = RequestMethod.GET,produce = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity< String> fetchCustomer()throws JsonProcessingException {
try {
String str = new ObjectMapper()。writeValueAsString(customerService.fetchAllCustomer());
返回新的ResponseEntity< String>(str,HttpStatus.OK);
}
catch(Exception e){
return new ResponseEntity< String>(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
}
}

如果有错误,可以使用控制器建议或捕获异常并适当地更新ResponseEntity


I am developing an application in jax-rs and spring mvc. I want to notify my client each time when an default error is occured like 400, 403, 404, 405 and 415.

Controller

    @Controller
    @RequestMapping("/customer")
    public class CustomerController {

        @Autowired
        CustomerService customerService;

        // ........xxxxxx..............xxxxxxx................xxxxxxx.............//


            @CrossOrigin
            @RequestMapping(value = "/", 
                            method = RequestMethod.GET, 
                            produces = MediaType.APPLICATION_JSON_VALUE)
            public @ResponseBody String fetchCustomer() throws JsonProcessingException {
                return new ObjectMapper().writeValueAsString(customerService.fetchAllCustomer());
            }

            // ........xxxxxx..............xxxxxxx................xxxxxxx.............//

}  

Client

$http({
        method: "GET",
        contentType: "application/json",
        url: baseUrl + '/customer'
      }).success(function (response) {
        console.log(response);
        // you can also use
        console.log(JSON.stringify(response);
      }).error(function (response) {
        console.log(response);
      });

When i request a service from client i want to send response back with status code and custom message.

Example

When i defind method = post on controller and from client i send request as get service should return message like

error:{
     Status Code: 405,
     Message:  Invalid Method 
     url: error/405
}

解决方案

Do not return a String but return a org.springframework.http.ResponseEntity. You can add status codes to this object

ResponseEntity<String> responseEntity = new ResponseEntity<String>("This is a response", HttpStatus.INTERNAL_SERVER_ERROR);
return responseEntity;

So your method signature will also change as below

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody ResponseEntity<String> fetchCustomer() throws JsonProcessingException {
        try {
            String str = new ObjectMapper().writeValueAsString(customerService.fetchAllCustomer());
            return new ResponseEntity<String>(str, HttpStatus.OK);
         }
        catch (Exception e) {
             return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

If there is an error, you can either use controller advice or catch the exception and update the ResponseEntity appropriately

这篇关于控制器SpringMVC处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆