1-9 SpringMVC 的异常处理 @ExceptionHandler

核心接口

    HandlerExceptionResolver

实现类

    SimpleMappingExceptionResolver

    DefaultHandlerExceptionResolver

    ResponseStatusExceptionResolver --顾名思义处理标记了 ResponseStatus的注解的方法或类

    ExceptionHandlerExceptionResolver

异常处理方法

    @ExceptionHandler

添加位置(advice优先级低)

    @Controller/@RestController 

    @ControllerAdvice/@RestControllerAdvice

Controller

    @PostMapping(path = "/getException",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Coffee getException(@RequestBody @Valid Coffee coffee,BindingResult result){
        if(result.hasErrors()){
            throw new ValidationException(result.toString());
        }
        return coffee;
    }

RestControllerAdvice

package com.example.ribi.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalControllerAdvice {
    @ExceptionHandler(ValidationException.class) //指定要处理哪一个异常类
    @ResponseStatus(HttpStatus.BAD_REQUEST) //指定要返回那种状态码
    public Map<String,String> validationExceptionHandler(ValidationException exception){
        Map<String,String> map = new HashMap<>();
        map.put("message",exception.getMessage());
        return map;
    }
}

Test

Post localhost:8080/user/getException raw  {"name":"coffee","money":12}
{
    "name": "coffee",
    "money": 12
}

Post localhost:8080/user/getException raw  {"money":12}
{
    "message": "org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object 'coffee' on field 'name': rejected value [null]; codes [NotEmpty.coffee.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [coffee.name,name]; arguments []; default message [name]]; default message [不能为空]"
}

--部分摘自极客时间玩转spring全家桶

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值